'use client';

import { useState } 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 { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Separator } from '@/components/ui/separator';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  ArrowLeft,
  Settings,
  User,
  Lock,
  Shield,
  Globe,
  Moon,
  Bell,
  Mail,
  Info,
  FileText,
  ShieldCheck,
  Trash2,
  ChevronRight,
  Loader2,
  Eye,
  EyeOff,
} from 'lucide-react';
import { useTheme } from 'next-themes';
import { useToast } from '@/hooks/use-toast';

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>
  );
}

// ============ CHANGE PASSWORD DIALOG ============
function ChangePasswordDialog({ open, onOpenChange }: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const { language, user } = useAppStore();
  const { toast } = useToast();
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!user?.id) {
      setError(language === 'en' ? 'You must be logged in to change your password.' : 'পাসওয়ার্ড পরিবর্তন করতে আপনাকে লগইন করতে হবে।');
      toast({
        title: language === 'en' ? 'Not Logged In' : 'লগইন নেই',
        description: language === 'en' ? 'Please log in to change your password.' : 'পাসওয়ার্ড পরিবর্তন করতে দয়া করে লগইন করুন।',
        variant: 'destructive',
        duration: 4000,
      });
      return;
    }
    setError('');

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

    if (newPassword.length < 6) {
      setError(t('profile.minPasswordLength', language));
      return;
    }

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

    if (currentPassword === newPassword) {
      setError(language === 'en' ? 'New password must be different from current password' : 'নতুন পাসওয়ার্ড বর্তমান পাসওয়ার্ড থেকে আলাদা হতে হবে');
      return;
    }

    setIsLoading(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) {
        toast({
          title: t('profile.passwordChanged', language),
          description: language === 'en'
            ? 'Your password has been updated successfully. Please use the new password next time you log in.'
            : 'আপনার পাসওয়ার্ড সফলভাবে আপডেট হয়েছে। পরবর্তী লগইনে নতুন পাসওয়ার্ড ব্যবহার করুন।',
          duration: 5000,
        });
        setCurrentPassword('');
        setNewPassword('');
        setConfirmPassword('');
        setShowCurrentPassword(false);
        setShowNewPassword(false);
        setShowConfirmPassword(false);
        onOpenChange(false);
      } else {
        const errorMessage = data.error || t('profile.wrongPassword', language);
        setError(errorMessage);
        toast({
          title: language === 'en' ? 'Change Password Failed' : 'পাসওয়ার্ড পরিবর্তন ব্যর্থ',
          description: errorMessage,
          variant: 'destructive',
          duration: 4000,
        });
      }
    } catch {
      const networkError = language === 'en' ? 'Network error. Please try again.' : 'নেটওয়ার্ক ত্রুটি। দয়া করে আবার চেষ্টা করুন।';
      setError(networkError);
      toast({
        title: language === 'en' ? 'Network Error' : 'নেটওয়ার্ক ত্রুটি',
        description: networkError,
        variant: 'destructive',
        duration: 4000,
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader className="flex-row items-center gap-2 space-y-0">
          <Button variant="ghost" size="sm" onClick={() => onOpenChange(false)} className="gap-1.5 text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-orange-950/30 -ml-2">
            <ArrowLeft className="h-4 w-4" />
            <span>{language === 'en' ? 'Back' : 'ফিরুন'}</span>
          </Button>
          <DialogTitle>{t('profile.changePassword', language)}</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          {error && (
            <div className="rounded-lg border border-destructive/20 bg-destructive/5 p-3 text-center text-sm text-destructive">
              {error}
            </div>
          )}
          <div className="space-y-2">
            <Label htmlFor="settings-current-pw">{t('profile.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="settings-current-pw"
                type={showCurrentPassword ? 'text' : 'password'}
                placeholder="••••••••"
                value={currentPassword}
                onChange={(e) => { setCurrentPassword(e.target.value); setError(''); }}
                className="pl-9 pr-10"
                required
              />
              <button
                type="button"
                onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                aria-label={showCurrentPassword ? 'Hide password' : 'Show password'}
              >
                {showCurrentPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
          </div>
          <div className="space-y-2">
            <Label htmlFor="settings-new-pw">{t('auth.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="settings-new-pw"
                type={showNewPassword ? 'text' : 'password'}
                placeholder="••••••••"
                value={newPassword}
                onChange={(e) => { setNewPassword(e.target.value); setError(''); }}
                className="pl-9 pr-10"
                required
                minLength={6}
              />
              <button
                type="button"
                onClick={() => setShowNewPassword(!showNewPassword)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                aria-label={showNewPassword ? 'Hide password' : 'Show password'}
              >
                {showNewPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
          </div>
          <div className="space-y-2">
            <Label htmlFor="settings-confirm-pw">{t('auth.confirmPassword', 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="settings-confirm-pw"
                type={showConfirmPassword ? 'text' : 'password'}
                placeholder="••••••••"
                value={confirmPassword}
                onChange={(e) => { setConfirmPassword(e.target.value); setError(''); }}
                className="pl-9 pr-10"
                required
                minLength={6}
              />
              <button
                type="button"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                aria-label={showConfirmPassword ? 'Hide password' : 'Show password'}
              >
                {showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
          </div>
          <Button type="submit" className="w-full" disabled={isLoading}>
            {isLoading ? (
              <span className="flex items-center gap-2">
                <Loader2 className="h-4 w-4 animate-spin" />
                {t('common.loading', language)}
              </span>
            ) : (
              t('profile.changePassword', language)
            )}
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}

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

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

  const isDarkMode = theme === 'dark';

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

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

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

  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">
          <Button variant="ghost" size="icon" onClick={() => setCurrentSection('home')} className="shrink-0 text-primary-foreground hover:bg-primary-foreground/20">
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <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={() => setCurrentSection('profile')}
          />
          <Separator className="mx-4" />
          <SettingItem
            icon={Lock}
            label={language === 'en' ? 'Change Password' : 'পাসওয়ার্ড পরিবর্তন'}
            onClick={() => {
              if (isLoggedIn) {
                setChangePassOpen(true);
              } else {
                setCurrentSection('auth');
              }
            }}
          />
          <Separator className="mx-4" />
          <SettingItem
            icon={Shield}
            label={t('settings.privacy', language)}
            onClick={() => {}}
          />
        </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 */}
        {isLoggedIn && (
          <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>

      {/* Change Password Dialog */}
      <ChangePasswordDialog
        open={changePassOpen}
        onOpenChange={setChangePassOpen}
      />
    </div>
  );
}
