import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { X, Paintbrush, Code2, Check, Trash2, AlertTriangle, LogOut, User } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Slider } from '@/components/ui/slider';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { useEditorStore } from '@/core/store';
import { useAuth } from '@/contexts/AuthContext';
import { useNavigate } from 'react-router-dom';
import { settingsApi, dataApi, authApi } from '@/lib/api';
import { languageModes } from '@/core/types';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { appleFadeIn, appleSpring } from '@/lib/apple-animations';

// Accent colors matching the design
const accentColors = [
  { value: 'blue', label: 'Blue', hex: '#3b82f6' },
  { value: 'green', label: 'Green', hex: '#10b981' },
  { value: 'purple', label: 'Purple', hex: '#8b5cf6' },
  { value: 'orange', label: 'Orange', hex: '#f97316' },
  { value: 'pink', label: 'Pink', hex: '#ec4899' },
  { value: 'red', label: 'Red', hex: '#ef4444' },
  { value: 'cyan', label: 'Cyan', hex: '#06b6d4' },
  { value: 'periwinkle', label: 'Periwinkle', hex: '#818cf8' },
  { value: 'teal', label: 'Teal', hex: '#14b8a6' },
  { value: 'yellow', label: 'Yellow', hex: '#eab308' },
  { value: 'lime', label: 'Lime', hex: '#84cc16' },
  { value: 'forest', label: 'Forest', hex: '#059669' },
  { value: 'lavender', label: 'Lavender', hex: '#c4b5fd' },
  { value: 'coral', label: 'Coral', hex: '#fb7185' },
  { value: 'sky', label: 'Sky', hex: '#38bdf8' },
  { value: 'royal', label: 'Royal', hex: '#a855f7' },
];

export const SettingsPanel: React.FC = () => {
  const { settings, updateSettings, loadSettings } = useEditorStore();
  const { logout, user, updateProfile } = useAuth();
  const navigate = useNavigate();
  const [deleteAccountDialogOpen, setDeleteAccountDialogOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [profileName, setProfileName] = useState(user?.name ?? '');
  const [profileEmail] = useState(user?.email ?? '');
  const [profileSaving, setProfileSaving] = useState(false);
  const [profileSaved, setProfileSaved] = useState(false);
  const [oldPassword, setOldPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [passwordSaving, setPasswordSaving] = useState(false);
  const [passwordSaved, setPasswordSaved] = useState(false);

  React.useEffect(() => {
    if (user) {
      setProfileName(user.name ?? '');
    }
  }, [user]);

  // Load settings on mount
  React.useEffect(() => {
    loadSettings();
  }, [loadSettings]);

  const handleDeleteAccount = async () => {
    setIsDeleting(true);
    try {
      // Clear all user data first
      await dataApi.clear();
      
      // Delete user account - we'll need to add this endpoint to the API
      // For now, clear data and logout (backend endpoint can be added later)
      toast.success('Account and all data deleted successfully');
      logout();
      navigate('/login');
    } catch (error: any) {
      console.error('Delete account error:', error);
      toast.error(error.message || 'Failed to delete account');
    } finally {
      setIsDeleting(false);
      setDeleteAccountDialogOpen(false);
    }
  };

  const handleSettingsUpdate = async (updates: Partial<typeof settings>) => {
    try {
      await updateSettings(updates);
    } catch (error) {
      console.error('Failed to update settings:', error);
      toast.error('Failed to update settings');
    }
  };

  const handleProfileSave = async () => {
    setProfileSaving(true);
    setProfileSaved(false);
    try {
      if (profileName.trim() === (user?.name ?? '')) {
        toast.info('No changes to save');
        return;
      }
      await updateProfile({ name: profileName.trim() || undefined });
      setProfileSaved(true);
      toast.success('Profile updated');
      setTimeout(() => setProfileSaved(false), 2000);
    } catch (error: any) {
      console.error('Profile update failed:', error);
      toast.error(error?.message ?? 'Failed to update profile');
    } finally {
      setProfileSaving(false);
    }
  };

  const handleChangePassword = async () => {
    if (!newPassword.trim() || !confirmPassword.trim() || !oldPassword.trim()) {
      toast.error('Fill in all password fields');
      return;
    }
    if (newPassword !== confirmPassword) {
      toast.error('New password and confirm password do not match');
      return;
    }
    if (newPassword.length < 6) {
      toast.error('New password must be at least 6 characters');
      return;
    }
    setPasswordSaving(true);
    setPasswordSaved(false);
    try {
      const verified = await authApi.verifyPassword(oldPassword);
      if (!verified?.valid) {
        toast.error('Current password is incorrect');
        return;
      }
      await updateProfile({ password: newPassword });
      setOldPassword('');
      setNewPassword('');
      setConfirmPassword('');
      setPasswordSaved(true);
      toast.success('Password updated');
      setTimeout(() => setPasswordSaved(false), 2000);
    } catch (error: any) {
      console.error('Password change failed:', error);
      toast.error(error?.message ?? 'Failed to change password');
    } finally {
      setPasswordSaving(false);
    }
  };

  return (
    <div className="h-full flex flex-col bg-background">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-sidebar-border">
        <h2 className="text-lg font-semibold">Settings</h2>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-auto apple-scroll">
        <Tabs defaultValue="profile" className="w-full">
          <div className="border-b border-sidebar-border px-4">
            <TabsList className="w-full justify-start bg-transparent h-auto p-0">
              <TabsTrigger 
                value="profile" 
                className="flex items-center gap-2 px-4 py-3 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
              >
                <User className="h-4 w-4" />
                Profile
              </TabsTrigger>
              <TabsTrigger 
                value="appearance" 
                className="flex items-center gap-2 px-4 py-3 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
              >
                <Paintbrush className="h-4 w-4" />
                Appearance
              </TabsTrigger>
              <TabsTrigger 
                value="editor" 
                className="flex items-center gap-2 px-4 py-3 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
              >
                <Code2 className="h-4 w-4" />
                Editor
              </TabsTrigger>
            </TabsList>
          </div>

          {/* Profile Tab - VS Code style: label + description + control */}
          <TabsContent value="profile" className="space-y-6 p-6 m-0">
            <div className="space-y-6 max-w-md">
              <div className="space-y-2">
                <Label className="text-sm font-medium">Display Name</Label>
                <p className="text-xs text-muted-foreground">Your name as shown in the status bar and across the app.</p>
                <Input
                  value={profileName}
                  onChange={(e) => setProfileName(e.target.value)}
                  placeholder="Your name"
                  className="w-full"
                />
              </div>
              <div className="space-y-2">
                <Label className="text-sm font-medium">Email</Label>
                <p className="text-xs text-muted-foreground">Used to sign in. Email cannot be changed here.</p>
                <Input
                  type="email"
                  value={user?.email ?? ''}
                  readOnly
                  placeholder="you@example.com"
                  className="w-full bg-muted/50 cursor-not-allowed"
                />
              </div>
              <div className="pt-2">
                <Button
                  onClick={handleProfileSave}
                  disabled={profileSaving}
                  className="gap-2"
                >
                  {profileSaving ? (
                    <>
                      <div className="w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin" />
                      Saving...
                    </>
                  ) : profileSaved ? (
                    <>
                      <Check className="h-4 w-4" />
                      Saved
                    </>
                  ) : (
                    'Update Profile'
                  )}
                </Button>
              </div>

              {/* Change Password - separate section */}
              <div className="border-t pt-6 mt-6 space-y-4">
                <Label className="text-sm font-medium">Change Password</Label>
                <p className="text-xs text-muted-foreground">Update your password. You must enter your current password.</p>
                <div className="space-y-3">
                  <div className="space-y-1.5">
                    <Label className="text-xs text-muted-foreground">Current password</Label>
                    <Input
                      type="password"
                      value={oldPassword}
                      onChange={(e) => setOldPassword(e.target.value)}
                      placeholder="••••••••"
                      className="w-full"
                      autoComplete="current-password"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label className="text-xs text-muted-foreground">New password</Label>
                    <Input
                      type="password"
                      value={newPassword}
                      onChange={(e) => setNewPassword(e.target.value)}
                      placeholder="••••••••"
                      className="w-full"
                      autoComplete="new-password"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label className="text-xs text-muted-foreground">Confirm new password</Label>
                    <Input
                      type="password"
                      value={confirmPassword}
                      onChange={(e) => setConfirmPassword(e.target.value)}
                      placeholder="••••••••"
                      className="w-full"
                      autoComplete="new-password"
                    />
                  </div>
                  <Button
                    variant="secondary"
                    onClick={handleChangePassword}
                    disabled={passwordSaving || !oldPassword.trim() || !newPassword.trim() || !confirmPassword.trim()}
                    className="gap-2"
                  >
                    {passwordSaving ? (
                      <>
                        <div className="w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin" />
                        Updating...
                      </>
                    ) : passwordSaved ? (
                      <>
                        <Check className="h-4 w-4" />
                        Password updated
                      </>
                    ) : (
                      'Change Password'
                    )}
                  </Button>
                </div>
              </div>
            </div>
          </TabsContent>

          {/* Appearance Tab */}
          <TabsContent value="appearance" className="space-y-6 p-6 m-0">
            <div className="space-y-6 max-w-md">
              {/* Theme */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">Theme</Label>
                <Select 
                  value={settings.theme || 'dark'} 
                  onValueChange={(value: 'light' | 'dark' | 'system') => handleSettingsUpdate({ theme: value })}
                >
                  <SelectTrigger className="w-full">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="light">Light</SelectItem>
                    <SelectItem value="dark">Dark</SelectItem>
                    <SelectItem value="system">System</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* Accent Color - compact grid */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">Accent Color</Label>
                <div className="grid grid-cols-8 gap-2">
                  {accentColors.map((color) => {
                    const isSelected = settings.accentColor === color.value;
                    return (
                      <motion.button
                        key={color.value}
                        onClick={() => handleSettingsUpdate({ accentColor: color.value })}
                        className={cn(
                          'relative w-8 h-8 rounded-md transition-all shrink-0',
                          'border-2',
                          isSelected
                            ? 'border-foreground ring-2 ring-offset-1 ring-primary'
                            : 'border-border hover:border-foreground/50'
                        )}
                        style={{ backgroundColor: color.hex }}
                        title={color.label}
                        whileHover={{ scale: 1.08 }}
                        whileTap={{ scale: 0.95 }}
                        transition={appleSpring}
                      >
                        {isSelected && (
                          <motion.div
                            initial={{ scale: 0 }}
                            animate={{ scale: 1 }}
                            className="absolute inset-0 flex items-center justify-center"
                          >
                            <div className="w-3.5 h-3.5 rounded-full bg-white/90 flex items-center justify-center shadow">
                              <Check className="h-2.5 w-2.5 text-foreground" />
                            </div>
                          </motion.div>
                        )}
                      </motion.button>
                    );
                  })}
                </div>
              </div>

              {/* Font Size */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <Label className="text-sm font-medium">Font Size</Label>
                  <span className="text-sm text-muted-foreground">{settings.fontSize || 14}px</span>
                </div>
                <Slider
                  value={[settings.fontSize || 14]}
                  onValueChange={([value]) => handleSettingsUpdate({ fontSize: value })}
                  min={10}
                  max={24}
                  step={1}
                  className="w-full"
                />
              </div>

              {/* Editor Font */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">Editor Font</Label>
                <Select 
                  value={settings.fontFamily || 'JetBrains Mono'} 
                  onValueChange={(value) => handleSettingsUpdate({ fontFamily: value })}
                >
                  <SelectTrigger className="w-full">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="JetBrains Mono">JetBrains Mono</SelectItem>
                    <SelectItem value="Fira Code">Fira Code</SelectItem>
                    <SelectItem value="Source Code Pro">Source Code Pro</SelectItem>
                    <SelectItem value="Cascadia Code">Cascadia Code</SelectItem>
                    <SelectItem value="SF Mono">SF Mono</SelectItem>
                    <SelectItem value="Monaco">Monaco</SelectItem>
                    <SelectItem value="Consolas">Consolas</SelectItem>
                    <SelectItem value="Courier New">Courier New</SelectItem>
                    <SelectItem value="Roboto Mono">Roboto Mono</SelectItem>
                    <SelectItem value="Inconsolata">Inconsolata</SelectItem>
                    <SelectItem value="Ubuntu Mono">Ubuntu Mono</SelectItem>
                    <SelectItem value="monospace">System Monospace</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </TabsContent>

          {/* Editor Tab */}
          <TabsContent value="editor" className="space-y-6 p-6 m-0">
            <div className="space-y-6 max-w-md">
              {/* Default Language */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">Default Language</Label>
                <Select 
                  value={settings.defaultLanguage || 'plaintext'} 
                  onValueChange={(value: any) => handleSettingsUpdate({ defaultLanguage: value })}
                >
                  <SelectTrigger className="w-full">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {languageModes.map(lang => (
                      <SelectItem key={lang.value} value={lang.value}>
                        {lang.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* Tab Size */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">Tab Size</Label>
                <Select 
                  value={(settings.tabSize || 2).toString()} 
                  onValueChange={(value) => handleSettingsUpdate({ tabSize: parseInt(value) })}
                >
                  <SelectTrigger className="w-full">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="2">2 spaces</SelectItem>
                    <SelectItem value="4">4 spaces</SelectItem>
                    <SelectItem value="8">8 spaces</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* Toggle Options */}
              <div className="space-y-4">
              <div className="flex items-center justify-between py-2">
                <div className="space-y-0.5">
                  <Label className="text-sm font-medium">Word Wrap</Label>
                  <p className="text-xs text-muted-foreground">Wrap long lines</p>
                </div>
                <Switch
                  checked={settings.wordWrap ?? true}
                  onCheckedChange={(checked) => handleSettingsUpdate({ wordWrap: checked })}
                />
              </div>

              <div className="flex items-center justify-between py-2">
                <div className="space-y-0.5">
                  <Label className="text-sm font-medium">Auto Save</Label>
                  <p className="text-xs text-muted-foreground">Save while typing</p>
                </div>
                <Switch
                  checked={settings.autoSave ?? true}
                  onCheckedChange={(checked) => handleSettingsUpdate({ autoSave: checked })}
                />
              </div>

              <div className="flex items-center justify-between py-2">
                <div className="space-y-0.5">
                  <Label className="text-sm font-medium">Line Numbers</Label>
                  <p className="text-xs text-muted-foreground">Show line numbers</p>
                </div>
                <Switch
                  checked={settings.lineNumbers ?? true}
                  onCheckedChange={(checked) => handleSettingsUpdate({ lineNumbers: checked })}
                />
              </div>

              <div className="flex items-center justify-between py-2">
                <div className="space-y-0.5">
                  <Label className="text-sm font-medium">Zen Mode</Label>
                  <p className="text-xs text-muted-foreground">Fullscreen distraction-free editing</p>
                </div>
                <Switch
                  checked={settings.zenMode ?? false}
                  onCheckedChange={(checked) => handleSettingsUpdate({ zenMode: checked })}
                />
              </div>
            </div>

              {/* Danger Zone - Delete Account */}
              <div className="border-t pt-6 mt-6">
                <div className="space-y-3">
                  <div className="flex items-center gap-2 text-destructive">
                    <AlertTriangle className="h-4 w-4" />
                    <Label className="text-sm font-medium text-destructive">Danger Zone</Label>
                  </div>
                  <p className="text-xs text-muted-foreground">
                    Permanently delete your account and all associated data. This action cannot be undone.
                  </p>
                  <Button 
                    onClick={() => setDeleteAccountDialogOpen(true)} 
                    variant="destructive" 
                    className="w-full"
                  >
                    <Trash2 className="h-4 w-4 mr-2" />
                    Delete Account
                  </Button>
                </div>
              </div>
            </div>
          </TabsContent>
        </Tabs>
      </div>

      {/* Delete Account Confirmation Dialog */}
      <AlertDialog open={deleteAccountDialogOpen} onOpenChange={setDeleteAccountDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2 text-destructive">
              <AlertTriangle className="h-5 w-5" />
              Delete Account Permanently
            </AlertDialogTitle>
            <AlertDialogDescription className="space-y-2 pt-2">
              <p>
                Are you absolutely sure you want to delete your account? This will permanently delete:
              </p>
              <ul className="list-disc list-inside space-y-1 text-sm">
                <li>All your notes and folders</li>
                <li>All your bookmarks</li>
                <li>All your settings</li>
                <li>Your account information</li>
              </ul>
              <p className="font-medium text-destructive mt-3">
                This action cannot be undone. Please type <strong>DELETE</strong> to confirm.
              </p>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
            <AlertDialogAction 
              onClick={handleDeleteAccount} 
              disabled={isDeleting}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {isDeleting ? (
                <>
                  <div className="w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin mr-2" />
                  Deleting...
                </>
              ) : (
                <>
                  <Trash2 className="h-4 w-4 mr-2" />
                  Delete Account
                </>
              )}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};

export default SettingsPanel;
