'use client';

import { useState, useRef } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { useToast } from '@/hooks/use-toast';
import {
  Settings,
  User,
  Lock,
  Shield,
  Globe,
  Moon,
  Bell,
  Mail,
  Info,
  FileText,
  ShieldCheck,
  Trash2,
  ChevronRight,
  Eye,
  EyeOff,
  Camera,
  ImagePlus,
} from 'lucide-react';
import { useTheme } from 'next-themes';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';

interface SettingItemProps {
  icon: React.ElementType;
  label: string;
  children?: React.ReactNode;
  onClick?: () => void;
  danger?: boolean;
}

function SettingItem({ icon: Icon, label, children, onClick, danger }: SettingItemProps) {
  const Wrapper = onClick ? 'button' : 'div';

  return (
    <Wrapper
      onClick={onClick}
      className={`flex w-full items-center gap-3 rounded-xl px-4 py-3 transition-colors duration-150 ${
        onClick ? 'hover:bg-accent active:bg-accent/80 cursor-pointer' : ''
      } ${danger ? 'text-destructive' : ''}`}
    >
      <Icon className={`h-5 w-5 ${danger ? 'text-destructive' : 'text-muted-foreground'}`} strokeWidth={1.75} />
      <span className={`flex-1 text-left text-sm font-medium ${danger ? 'text-destructive' : 'text-foreground'}`}>
        {label}
      </span>
      {children || (
        onClick && <ChevronRight className="h-4 w-4 text-muted-foreground/50" />
      )}
    </Wrapper>
  );
}

interface SettingSectionProps {
  title: string;
  children: React.ReactNode;
}

function SettingSection({ title, children }: SettingSectionProps) {
  return (
    <div className="space-y-2">
      <h3 className="px-1 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
        {title}
      </h3>
      <Card>
        <CardContent className="p-2">
          {children}
        </CardContent>
      </Card>
    </div>
  );
}

const quickAvatars = [
  { emoji: '😊', bg: 'bg-amber-100 dark:bg-amber-900/30' },
  { emoji: '👨', bg: 'bg-sky-100 dark:bg-sky-900/30' },
  { emoji: '👩', bg: 'bg-pink-100 dark:bg-pink-900/30' },
  { emoji: '🧑', bg: 'bg-emerald-100 dark:bg-emerald-900/30' },
  { emoji: '👦', bg: 'bg-violet-100 dark:bg-violet-900/30' },
  { emoji: '👧', bg: 'bg-rose-100 dark:bg-rose-900/30' },
  { emoji: '👴', bg: 'bg-gray-100 dark:bg-gray-800' },
  { emoji: '👵', bg: 'bg-teal-100 dark:bg-teal-900/30' },
  { emoji: '🧔', bg: 'bg-orange-100 dark:bg-orange-900/30' },
  { emoji: '👱', bg: 'bg-yellow-100 dark:bg-yellow-900/30' },
  { emoji: '🧕', bg: 'bg-indigo-100 dark:bg-indigo-900/30' },
  { emoji: '👲', bg: 'bg-lime-100 dark:bg-lime-900/30' },
];

export default function SettingsModule() {
  const { language, setLanguage, logout, user, updateUser } = useAppStore();
  const { theme, setTheme } = useTheme();
  const { toast } = useToast();

  const [pushNotifications, setPushNotifications] = useState(true);
  const [emailNotifications, setEmailNotifications] = useState(false);

  const isDarkMode = theme === 'dark';

  // Edit Profile dialog state
  const [editProfileOpen, setEditProfileOpen] = useState(false);
  const [editName, setEditName] = useState('');
  const [editEmail, setEditEmail] = useState('');
  const [editPhone, setEditPhone] = useState('');
  const [editAvatar, setEditAvatar] = useState<string | undefined>(undefined);
  const [editProfileLoading, setEditProfileLoading] = useState(false);
  const [avatarPickerOpen, setAvatarPickerOpen] = useState(false);
  const editFileInputRef = useRef<HTMLInputElement>(null);

  // Change Password dialog state
  const [changePasswordOpen, setChangePasswordOpen] = useState(false);
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [passwordError, setPasswordError] = useState('');
  const [changePasswordLoading, setChangePasswordLoading] = useState(false);

  // Privacy dialog state - initialize from localStorage
  const [privacyOpen, setPrivacyOpen] = useState(false);
  const [showPhone, setShowPhone] = useState(() => {
    try {
      const saved = localStorage.getItem('needyfy-privacy-settings');
      if (saved) return JSON.parse(saved).showPhone ?? false;
    } catch { /* ignore */ }
    return false;
  });
  const [showEmail, setShowEmail] = useState(() => {
    try {
      const saved = localStorage.getItem('needyfy-privacy-settings');
      if (saved) return JSON.parse(saved).showEmail ?? false;
    } catch { /* ignore */ }
    return false;
  });
  const [showProfile, setShowProfile] = useState(() => {
    try {
      const saved = localStorage.getItem('needyfy-privacy-settings');
      if (saved) return JSON.parse(saved).showProfile ?? true;
    } catch { /* ignore */ }
    return true;
  });
  const [allowMessages, setAllowMessages] = useState(() => {
    try {
      const saved = localStorage.getItem('needyfy-privacy-settings');
      if (saved) return JSON.parse(saved).allowMessages ?? true;
    } catch { /* ignore */ }
    return true;
  });

  const handleDarkModeToggle = (checked: boolean) => {
    setTheme(checked ? 'dark' : 'light');
  };

  const handleLanguageToggle = () => {
    setLanguage(language === 'en' ? 'bn' : 'en');
  };

  const handleDeleteAccount = () => {
    logout();
  };

  // Edit Profile handler - now persists to database
  const handleSaveProfile = async () => {
    if (!editName.trim() || !editEmail.trim() || !user?.id) return;
    setEditProfileLoading(true);

    try {
      const res = await fetch('/api/auth/update-profile', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: user.id,
          name: editName.trim(),
          email: editEmail.trim(),
          phone: editPhone.trim() || undefined,
          avatar: editAvatar !== undefined ? editAvatar : user.avatar,
        }),
      });

      const data = await res.json();

      if (res.ok) {
        // Update local store
        updateUser({
          name: data.user.name,
          email: data.user.email,
          phone: data.user.phone || undefined,
          avatar: data.user.avatar || undefined,
        });
        setEditProfileOpen(false);
        toast({
          title: language === 'en' ? 'Success!' : 'সফল!',
          description: t('settings.profileUpdated', language),
          duration: 3000,
        });
      } else {
        toast({
          title: language === 'en' ? 'Error' : 'ত্রুটি',
          description: data.error || (language === 'en' ? 'Failed to update profile' : 'প্রোফাইল আপডেট ব্যর্থ'),
          variant: 'destructive',
        });
      }
    } catch {
      toast({
        title: language === 'en' ? 'Network Error' : 'নেটওয়ার্ক ত্রুটি',
        description: language === 'en' ? 'Please try again' : 'আবার চেষ্টা করুন',
        variant: 'destructive',
      });
    } finally {
      setEditProfileLoading(false);
    }
  };

  // Change Password handler - now actually changes password in database
  const handleChangePassword = async () => {
    setPasswordError('');

    if (!currentPassword) {
      setPasswordError(language === 'en' ? 'Please enter your current password' : 'আপনার বর্তমান পাসওয়ার্ড লিখুন');
      return;
    }

    if (!newPassword) {
      setPasswordError(language === 'en' ? 'Please enter a new password' : 'একটি নতুন পাসওয়ার্ড লিখুন');
      return;
    }

    if (newPassword.length < 6) {
      setPasswordError(language === 'en' ? 'Password must be at least 6 characters' : 'পাসওয়ার্ড কমপক্ষে ৬ অক্ষরের হতে হবে');
      return;
    }

    if (newPassword !== confirmPassword) {
      setPasswordError(t('settings.passwordMismatch', language));
      return;
    }

    if (!user?.id) return;

    setChangePasswordLoading(true);

    try {
      const res = await fetch('/api/auth/change-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: user.id,
          currentPassword,
          newPassword,
        }),
      });

      const data = await res.json();

      if (res.ok) {
        setChangePasswordOpen(false);
        setCurrentPassword('');
        setNewPassword('');
        setConfirmPassword('');
        setPasswordError('');
        toast({
          title: language === 'en' ? 'Success!' : 'সফল!',
          description: t('settings.passwordChanged', language),
          duration: 3000,
        });
      } else {
        setPasswordError(data.error || (language === 'en' ? 'Failed to change password' : 'পাসওয়ার্ড পরিবর্তন ব্যর্থ'));
      }
    } catch {
      setPasswordError(language === 'en' ? 'Network error. Please try again.' : 'নেটওয়ার্ক ত্রুটি। আবার চেষ্টা করুন।');
    } finally {
      setChangePasswordLoading(false);
    }
  };

  // Privacy save handler
  const handleSavePrivacy = () => {
    const settings = { showPhone, showEmail, showProfile, allowMessages };
    localStorage.setItem('needyfy-privacy-settings', JSON.stringify(settings));
    setPrivacyOpen(false);
    toast({
      title: language === 'en' ? 'Success!' : 'সফল!',
      description: t('settings.privacySaved', language),
      duration: 3000,
    });
  };

  // Handle avatar selection in edit profile
  const handleSelectQuickAvatar = (emoji: string) => {
    setEditAvatar(emoji);
    setAvatarPickerOpen(false);
  };

  const handleGallerySelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        const dataUrl = event.target?.result as string;
        setEditAvatar(dataUrl);
        setAvatarPickerOpen(false);
      };
      reader.readAsDataURL(file);
    }
    e.target.value = '';
  };

  // Determine avatar display in edit profile
  const renderEditAvatar = () => {
    const avatarSrc = editAvatar;
    if (!avatarSrc) {
      return (
        <div className="flex h-20 w-20 items-center justify-center rounded-full bg-primary/10">
          <User className="h-8 w-8 text-primary/40" />
        </div>
      );
    }
    const isEmoji = !avatarSrc.startsWith('data:') && !avatarSrc.startsWith('http');
    const isImage = avatarSrc.startsWith('data:') || avatarSrc.startsWith('http');

    if (isImage) {
      return (
        <Avatar className="h-20 w-20 border-2 border-primary/20">
          <AvatarImage src={avatarSrc} alt="Profile" className="object-cover" />
          <AvatarFallback className="bg-primary/10">
            <User className="h-8 w-8 text-primary/40" />
          </AvatarFallback>
        </Avatar>
      );
    }

    return (
      <div className="flex h-20 w-20 items-center justify-center rounded-full bg-primary/10 text-4xl">
        {avatarSrc}
      </div>
    );
  };

  return (
    <div className="custom-scrollbar flex min-h-[calc(100vh-8rem)] flex-col overflow-y-auto pb-6">
      {/* Header */}
      <div className="bg-gradient-to-br from-primary via-primary/90 to-primary/70 px-6 pb-6 pt-6">
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-primary-foreground/20">
            <Settings className="h-5 w-5 text-primary-foreground" strokeWidth={1.75} />
          </div>
          <div>
            <h1 className="text-xl font-bold text-primary-foreground">
              {t('settings.title', language)}
            </h1>
            <p className="text-xs text-primary-foreground/70">
              {language === 'en' ? 'Manage your preferences' : 'আপনার পছন্দ পরিচালনা করুন'}
            </p>
          </div>
        </div>
      </div>

      {/* Settings Sections */}
      <div className="mt-4 space-y-6 px-4">
        {/* Account Section */}
        <SettingSection title={language === 'en' ? 'Account' : 'অ্যাকাউন্ট'}>
          <SettingItem
            icon={User}
            label={t('profile.editProfile', language)}
            onClick={() => {
              if (user) {
                setEditName(user.name);
                setEditEmail(user.email);
                setEditPhone(user.phone || '');
                setEditAvatar(user.avatar || undefined);
              }
              setEditProfileOpen(true);
            }}
          />
          <Separator className="mx-4" />
          <SettingItem
            icon={Lock}
            label={t('settings.changePassword', language)}
            onClick={() => {
              setCurrentPassword('');
              setNewPassword('');
              setConfirmPassword('');
              setPasswordError('');
              setChangePasswordOpen(true);
            }}
          />
          <Separator className="mx-4" />
          <SettingItem
            icon={Shield}
            label={t('settings.privacy', language)}
            onClick={() => setPrivacyOpen(true)}
          />
        </SettingSection>

        {/* Preferences Section */}
        <SettingSection title={language === 'en' ? 'Preferences' : 'পছন্দ'}>
          <SettingItem
            icon={Globe}
            label={t('settings.language', language)}
          >
            <button
              onClick={handleLanguageToggle}
              className="flex items-center gap-2 rounded-full bg-muted p-1 transition-colors duration-150"
            >
              <span
                className={`rounded-full px-3 py-1 text-xs font-medium transition-colors duration-150 ${
                  language === 'en'
                    ? 'bg-primary text-primary-foreground shadow-sm'
                    : 'text-muted-foreground'
                }`}
              >
                EN
              </span>
              <span
                className={`rounded-full px-3 py-1 text-xs font-medium transition-colors duration-150 ${
                  language === 'bn'
                    ? 'bg-primary text-primary-foreground shadow-sm'
                    : 'text-muted-foreground'
                }`}
              >
                বাং
              </span>
            </button>
          </SettingItem>
          <Separator className="mx-4" />
          <SettingItem
            icon={Moon}
            label={t('sidebar.darkMode', language)}
          >
            <Switch
              checked={isDarkMode}
              onCheckedChange={handleDarkModeToggle}
              aria-label="Toggle dark mode"
            />
          </SettingItem>
        </SettingSection>

        {/* Notifications Section */}
        <SettingSection title={t('settings.notifications', language)}>
          <SettingItem
            icon={Bell}
            label={language === 'en' ? 'Push Notifications' : 'পুশ বিজ্ঞপ্তি'}
          >
            <Switch
              checked={pushNotifications}
              onCheckedChange={setPushNotifications}
              aria-label="Toggle push notifications"
            />
          </SettingItem>
          <Separator className="mx-4" />
          <SettingItem
            icon={Mail}
            label={language === 'en' ? 'Email Notifications' : 'ইমেইল বিজ্ঞপ্তি'}
          >
            <Switch
              checked={emailNotifications}
              onCheckedChange={setEmailNotifications}
              aria-label="Toggle email notifications"
            />
          </SettingItem>
        </SettingSection>

        {/* About Section */}
        <SettingSection title={t('settings.about', language)}>
          <SettingItem
            icon={Info}
            label={language === 'en' ? 'App Version' : 'অ্যাপ ভার্সন'}
          >
            <span className="text-xs text-muted-foreground">1.0.0</span>
          </SettingItem>
          <Separator className="mx-4" />
          <SettingItem
            icon={FileText}
            label={language === 'en' ? 'Terms of Service' : 'সেবার শর্তাবলী'}
            onClick={() => {}}
          />
          <Separator className="mx-4" />
          <SettingItem
            icon={ShieldCheck}
            label={language === 'en' ? 'Privacy Policy' : 'গোপনীয়তা নীতি'}
            onClick={() => {}}
          />
        </SettingSection>

        {/* Danger Zone */}
        <SettingSection title={language === 'en' ? 'Danger Zone' : 'বিপজ্জনক জোন'}>
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <button className="flex w-full items-center gap-3 rounded-xl px-4 py-3 text-destructive transition-colors duration-150 hover:bg-destructive/5">
                <Trash2 className="h-5 w-5 text-destructive" strokeWidth={1.75} />
                <span className="flex-1 text-left text-sm font-medium text-destructive">
                  {language === 'en' ? 'Delete Account' : 'অ্যাকাউন্ট মুছুন'}
                </span>
                <ChevronRight className="h-4 w-4 text-destructive/50" />
              </button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle className="text-destructive">
                  {language === 'en' ? 'Delete Account?' : 'অ্যাকাউন্ট মুছবেন?'}
                </AlertDialogTitle>
                <AlertDialogDescription>
                  {language === 'en'
                    ? 'This action cannot be undone. This will permanently delete your account and remove all your data from our servers.'
                    : 'এই কাজটি পূর্বাবস্থায় ফেরানো যাবে না। এটি স্থায়ীভাবে আপনার অ্যাকাউন্ট মুছে ফেলবে এবং আমাদের সার্ভার থেকে আপনার সমস্ত ডেটা সরিয়ে দেবে।'}
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>
                  {t('common.cancel', language)}
                </AlertDialogCancel>
                <AlertDialogAction
                  onClick={handleDeleteAccount}
                  className="bg-destructive text-white hover:bg-destructive/90"
                >
                  {t('common.delete', language)}
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        </SettingSection>

        {/* Footer info */}
        <div className="pb-4 text-center">
          <img
            src="/logo-needyfy.png"
            alt="Needyfy Logo"
            className="mx-auto mb-2 h-10 w-10 rounded-xl object-cover"
          />
          <p className="text-[11px] text-muted-foreground">
            {t('app.name', language)} v1.0.0
          </p>
          <p className="text-[10px] text-muted-foreground/60">
            {t('app.tagline', language)}
          </p>
        </div>
      </div>

      {/* Edit Profile Dialog - with profile picture upload */}
      <Dialog open={editProfileOpen} onOpenChange={setEditProfileOpen}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle>{t('profile.editProfile', language)}</DialogTitle>
            <DialogDescription>
              {language === 'en'
                ? 'Update your personal information'
                : 'আপনার ব্যক্তিগত তথ্য আপডেট করুন'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            {/* Profile Picture Section */}
            <div className="flex flex-col items-center gap-3">
              <div className="relative">
                {renderEditAvatar()}
                <button
                  className="absolute bottom-0 right-0 flex h-7 w-7 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-md transition-transform hover:scale-105 active:scale-95"
                  onClick={() => setAvatarPickerOpen(true)}
                  aria-label="Change profile picture"
                >
                  <Camera className="h-3.5 w-3.5" />
                </button>
              </div>
              <button
                className="text-xs font-medium text-primary hover:underline"
                onClick={() => setAvatarPickerOpen(true)}
              >
                {language === 'en' ? 'Change Profile Picture' : 'প্রোফাইল ছবি পরিবর্তন'}
              </button>
            </div>

            <Separator />

            <div className="space-y-2">
              <Label htmlFor="edit-name">{t('auth.name', language)}</Label>
              <div className="relative">
                <User className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  id="edit-name"
                  type="text"
                  value={editName}
                  onChange={(e) => setEditName(e.target.value)}
                  className="pl-9"
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="edit-email">{t('auth.email', language)}</Label>
              <div className="relative">
                <Mail className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  id="edit-email"
                  type="email"
                  value={editEmail}
                  onChange={(e) => setEditEmail(e.target.value)}
                  className="pl-9"
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="edit-phone">{t('auth.phone', language)}</Label>
              <div className="relative">
                <User className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  id="edit-phone"
                  type="tel"
                  value={editPhone}
                  onChange={(e) => setEditPhone(e.target.value)}
                  className="pl-9"
                  placeholder="+880 1XXX-XXXXXX"
                />
              </div>
            </div>
            <div className="flex gap-3">
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => setEditProfileOpen(false)}
              >
                {t('common.cancel', language)}
              </Button>
              <Button
                className="flex-1"
                onClick={handleSaveProfile}
                disabled={!editName.trim() || !editEmail.trim() || editProfileLoading}
              >
                {editProfileLoading ? (
                  <span className="flex items-center gap-2">
                    <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                    {t('common.loading', language)}
                  </span>
                ) : (
                  t('common.save', language)
                )}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Avatar Picker Dialog (nested inside edit profile) */}
      <Dialog open={avatarPickerOpen} onOpenChange={setAvatarPickerOpen}>
        <DialogContent className="sm:max-w-[380px]">
          <DialogHeader>
            <DialogTitle>{language === 'en' ? 'Change Profile Picture' : 'প্রোফাইল ছবি পরিবর্তন'}</DialogTitle>
            <DialogDescription>
              {language === 'en'
                ? 'Choose a quick avatar or upload your own photo'
                : 'একটি দ্রুত অবতার বেছে নিন বা আপনার নিজের ছবি আপলোড করুন'}
            </DialogDescription>
          </DialogHeader>

          {/* Quick Avatars Grid */}
          <div className="space-y-3">
            <h4 className="text-sm font-medium text-muted-foreground">
              {language === 'en' ? 'Quick Avatars' : 'দ্রুত অবতার'}
            </h4>
            <div className="grid grid-cols-4 gap-3">
              {quickAvatars.map((avatar) => (
                <button
                  key={avatar.emoji}
                  onClick={() => handleSelectQuickAvatar(avatar.emoji)}
                  className={`flex h-14 w-full items-center justify-center rounded-full text-2xl transition-all duration-150 hover:scale-110 active:scale-95 ${avatar.bg} ${
                    editAvatar === avatar.emoji ? 'ring-2 ring-primary ring-offset-2' : ''
                  }`}
                >
                  {avatar.emoji}
                </button>
              ))}
            </div>
          </div>

          <Separator />

          {/* Add from Gallery */}
          <div className="space-y-3">
            <h4 className="text-sm font-medium text-muted-foreground">
              {language === 'en' ? 'Upload Photo' : 'ছবি আপলোড'}
            </h4>
            <Button
              variant="outline"
              className="w-full gap-2"
              onClick={() => editFileInputRef.current?.click()}
            >
              <ImagePlus className="h-4 w-4" />
              {language === 'en' ? 'Choose Photo' : 'ছবি বেছে নিন'}
            </Button>
            <input
              ref={editFileInputRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={handleGallerySelect}
            />
          </div>

          {/* Preview & Remove */}
          {editAvatar && (
            <>
              <Separator />
              <div className="flex items-center gap-3">
                <span className="text-xs text-muted-foreground">
                  {language === 'en' ? 'Current:' : 'বর্তমান:'}
                </span>
                <div className="h-10 w-10 overflow-hidden rounded-full bg-primary/10">
                  {(editAvatar.startsWith('data:') || editAvatar.startsWith('http')) ? (
                    <img src={editAvatar} alt="Avatar" className="h-full w-full object-cover" />
                  ) : (
                    <div className="flex h-full w-full items-center justify-center text-xl">
                      {editAvatar}
                    </div>
                  )}
                </div>
                <Button
                  variant="ghost"
                  size="sm"
                  className="ml-auto text-xs text-destructive hover:text-destructive"
                  onClick={() => {
                    setEditAvatar(undefined);
                    setAvatarPickerOpen(false);
                  }}
                >
                  {language === 'en' ? 'Remove' : 'সরান'}
                </Button>
              </div>
            </>
          )}
        </DialogContent>
      </Dialog>

      {/* Change Password Dialog */}
      <Dialog open={changePasswordOpen} onOpenChange={(open) => {
        if (!open) {
          setCurrentPassword('');
          setNewPassword('');
          setConfirmPassword('');
          setPasswordError('');
        }
        setChangePasswordOpen(open);
      }}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle>{t('settings.changePassword', language)}</DialogTitle>
            <DialogDescription>
              {language === 'en'
                ? 'Enter your current password and choose a new one'
                : 'আপনার বর্তমান পাসওয়ার্ড লিখুন এবং একটি নতুন নির্বাচন করুন'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="current-password">{t('settings.currentPassword', language)}</Label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  id="current-password"
                  type={showCurrentPassword ? 'text' : 'password'}
                  value={currentPassword}
                  onChange={(e) => { setCurrentPassword(e.target.value); setPasswordError(''); }}
                  className="pl-9 pr-10"
                  placeholder="••••••••"
                />
                <button
                  type="button"
                  onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                >
                  {showCurrentPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="new-password-settings">{t('settings.newPassword', language)}</Label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  id="new-password-settings"
                  type={showNewPassword ? 'text' : 'password'}
                  value={newPassword}
                  onChange={(e) => { setNewPassword(e.target.value); setPasswordError(''); }}
                  className="pl-9 pr-10"
                  placeholder="••••••••"
                />
                <button
                  type="button"
                  onClick={() => setShowNewPassword(!showNewPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                >
                  {showNewPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="confirm-new-password">{t('settings.confirmNewPassword', language)}</Label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  id="confirm-new-password"
                  type="password"
                  value={confirmPassword}
                  onChange={(e) => { setConfirmPassword(e.target.value); setPasswordError(''); }}
                  className="pl-9"
                  placeholder="••••••••"
                />
              </div>
            </div>
            {passwordError && (
              <p className="text-xs text-destructive">{passwordError}</p>
            )}
            <div className="flex gap-3">
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => setChangePasswordOpen(false)}
              >
                {t('common.cancel', language)}
              </Button>
              <Button
                className="flex-1"
                onClick={handleChangePassword}
                disabled={!currentPassword || !newPassword || !confirmPassword || changePasswordLoading}
              >
                {changePasswordLoading ? (
                  <span className="flex items-center gap-2">
                    <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                    {t('common.loading', language)}
                  </span>
                ) : (
                  t('common.save', language)
                )}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Privacy Settings Dialog */}
      <Dialog open={privacyOpen} onOpenChange={setPrivacyOpen}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle>{t('settings.privacy', language)}</DialogTitle>
            <DialogDescription>
              {language === 'en'
                ? 'Control who can see your information'
                : 'কে আপনার তথ্য দেখতে পারবে তা নিয়ন্ত্রণ করুন'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-5">
            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label className="text-sm font-medium">{t('settings.showPhone', language)}</Label>
                <p className="text-[11px] text-muted-foreground">
                  {language === 'en' ? 'Others can see your phone number' : 'অন্যরা আপনার ফোন নম্বর দেখতে পারবে'}
                </p>
              </div>
              <Switch
                checked={showPhone}
                onCheckedChange={setShowPhone}
                aria-label="Toggle show phone number"
              />
            </div>
            <Separator />
            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label className="text-sm font-medium">{t('settings.showEmail', language)}</Label>
                <p className="text-[11px] text-muted-foreground">
                  {language === 'en' ? 'Others can see your email address' : 'অন্যরা আপনার ইমেইল দেখতে পারবে'}
                </p>
              </div>
              <Switch
                checked={showEmail}
                onCheckedChange={setShowEmail}
                aria-label="Toggle show email"
              />
            </div>
            <Separator />
            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label className="text-sm font-medium">{t('settings.showProfile', language)}</Label>
                <p className="text-[11px] text-muted-foreground">
                  {language === 'en' ? 'Your profile is visible to other users' : 'আপনার প্রোফাইল অন্য ব্যবহারকারীদের দেখা যাবে'}
                </p>
              </div>
              <Switch
                checked={showProfile}
                onCheckedChange={setShowProfile}
                aria-label="Toggle show profile"
              />
            </div>
            <Separator />
            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label className="text-sm font-medium">{t('settings.allowMessages', language)}</Label>
                <p className="text-[11px] text-muted-foreground">
                  {language === 'en' ? 'Anyone can send you messages' : 'যে কেউ আপনাকে মেসেজ পাঠাতে পারবে'}
                </p>
              </div>
              <Switch
                checked={allowMessages}
                onCheckedChange={setAllowMessages}
                aria-label="Toggle allow messages"
              />
            </div>
            <Button onClick={handleSavePrivacy} className="w-full">
              {t('common.save', language)}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
