import { useState, type FormEvent } from 'react';
import { motion } from 'framer-motion';
import { User, Lock, Bell, AlertTriangle, Shield } from 'lucide-react';
import { PageTransition } from '@/components/layout/PageTransition';
import { Card } from '@/components/ui/Card';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { Toggle } from '@/components/ui/Toggle';
import { Modal } from '@/components/ui/Modal';
import { useToast } from '@/components/ui/Toast';
import { useAuthStore } from '@/stores/authStore';
import { staggerContainer, staggerItem } from '@/lib/animations';

export default function Settings() {
  const user = useAuthStore((s) => s.user);
  const { toast } = useToast();
  const [username, setUsername] = useState(user?.username || '');
  const [email, setEmail] = useState(user?.email || '');
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [notifications, setNotifications] = useState(true);
  const [deleteModal, setDeleteModal] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState('');

  function handleSaveAccount(e: FormEvent) {
    e.preventDefault();
    if (!username.trim()) {
      toast('Username cannot be empty', 'error');
      return;
    }
    toast('Account settings saved', 'success');
  }

  function handleChangePassword(e: FormEvent) {
    e.preventDefault();
    if (!currentPassword || !newPassword) {
      toast('Please fill in all password fields', 'warning');
      return;
    }
    if (newPassword.length < 8) {
      toast('Password must be at least 8 characters', 'error');
      return;
    }
    if (newPassword !== confirmPassword) {
      toast('Passwords do not match', 'error');
      return;
    }
    toast('Password changed successfully', 'success');
    setCurrentPassword('');
    setNewPassword('');
    setConfirmPassword('');
  }

  return (
    <PageTransition className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <motion.div
        initial={{ opacity: 0, y: 8 }}
        animate={{ opacity: 1, y: 0 }}
        className="mb-8"
      >
        <h1 className="text-2xl sm:text-3xl font-extrabold text-[#f0f0f5] tracking-tight">
          Settings
        </h1>
        <p className="text-sm text-[#a0a0b8] mt-1">
          Manage your account preferences
        </p>
      </motion.div>

      <motion.div variants={staggerContainer} initial="initial" animate="animate" className="space-y-8">
        <motion.div variants={staggerItem}>
          <Card className="relative overflow-hidden">
            <div className="absolute top-0 left-0 right-0 h-0.5 bg-[#ff6b2c]/30" />
            <div className="flex items-center gap-2 mb-6">
              <div className="w-8 h-8 rounded-lg bg-[#ff6b2c]/10 flex items-center justify-center">
                <User className="w-4 h-4 text-[#ff6b2c]" />
              </div>
              <h2 className="text-sm font-bold text-[#f0f0f5] uppercase tracking-wider">Account</h2>
            </div>
            <form onSubmit={handleSaveAccount} className="space-y-4">
              <Input
                label="Username"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
              />
              <Input
                label="Email"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
              <div className="flex justify-end pt-2">
                <Button type="submit">Save Changes</Button>
              </div>
            </form>
          </Card>
        </motion.div>

        <motion.div variants={staggerItem}>
          <Card className="relative overflow-hidden">
            <div className="absolute top-0 left-0 right-0 h-0.5 bg-blue-500/30" />
            <div className="flex items-center gap-2 mb-6">
              <div className="w-8 h-8 rounded-lg bg-blue-500/10 flex items-center justify-center">
                <Lock className="w-4 h-4 text-blue-500" />
              </div>
              <h2 className="text-sm font-bold text-[#f0f0f5] uppercase tracking-wider">Change Password</h2>
            </div>
            <form onSubmit={handleChangePassword} className="space-y-4">
              <Input
                label="Current Password"
                type="password"
                value={currentPassword}
                onChange={(e) => setCurrentPassword(e.target.value)}
              />
              <Input
                label="New Password"
                type="password"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
              />
              <Input
                label="Confirm New Password"
                type="password"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
              />
              <div className="flex justify-end pt-2">
                <Button type="submit">Update Password</Button>
              </div>
            </form>
          </Card>
        </motion.div>

        <motion.div variants={staggerItem}>
          <Card className="relative overflow-hidden">
            <div className="absolute top-0 left-0 right-0 h-0.5 bg-purple-500/30" />
            <div className="flex items-center gap-2 mb-6">
              <div className="w-8 h-8 rounded-lg bg-purple-500/10 flex items-center justify-center">
                <Bell className="w-4 h-4 text-purple-500" />
              </div>
              <h2 className="text-sm font-bold text-[#f0f0f5] uppercase tracking-wider">Notifications</h2>
            </div>
            <div className="space-y-4">
              <Toggle
                checked={notifications}
                onChange={setNotifications}
                label="Browser notifications for match found and results"
              />
            </div>
          </Card>
        </motion.div>

        <motion.div variants={staggerItem}>
          <Card className="relative overflow-hidden border-red-500/20">
            <div className="absolute top-0 left-0 right-0 h-0.5 bg-red-500/50" />
            <div className="flex items-center gap-2 mb-4">
              <div className="w-8 h-8 rounded-lg bg-red-500/10 flex items-center justify-center">
                <AlertTriangle className="w-4 h-4 text-red-500" />
              </div>
              <h2 className="text-sm font-bold text-red-400 uppercase tracking-wider">Danger Zone</h2>
            </div>
            <p className="text-sm text-[#a0a0b8] mb-4">
              Permanently delete your account and all associated data. This action cannot be undone.
            </p>
            <Button variant="danger" onClick={() => setDeleteModal(true)}>
              <AlertTriangle className="w-4 h-4" />
              Delete Account
            </Button>
          </Card>
        </motion.div>
      </motion.div>

      <Modal open={deleteModal} onClose={() => setDeleteModal(false)} title="Delete Account">
        <div className="flex items-center gap-3 mb-4 p-3 bg-red-500/10 border border-red-500/20 rounded-xl">
          <Shield className="w-5 h-5 text-red-400 flex-shrink-0" />
          <p className="text-sm text-[#a0a0b8]">
            This action is <span className="text-red-400 font-medium">permanent and irreversible</span>.
            All your match history, stats, and account data will be deleted.
          </p>
        </div>
        <p className="text-sm text-[#a0a0b8] mb-4">
          Type <span className="font-mono text-red-400 bg-red-500/10 px-1.5 py-0.5 rounded">{user?.username}</span> to confirm.
        </p>
        <Input
          label="Type your username"
          value={deleteConfirm}
          onChange={(e) => setDeleteConfirm(e.target.value)}
          error={deleteConfirm.length > 0 && deleteConfirm !== user?.username ? 'Username does not match' : undefined}
        />
        <div className="flex justify-end gap-3 mt-6">
          <Button variant="secondary" onClick={() => { setDeleteModal(false); setDeleteConfirm(''); }}>
            Cancel
          </Button>
          <Button
            variant="danger"
            disabled={deleteConfirm !== user?.username}
            onClick={() => {
              toast('Account deletion is not yet implemented', 'info');
              setDeleteModal(false);
              setDeleteConfirm('');
            }}
          >
            Delete Forever
          </Button>
        </div>
      </Modal>
    </PageTransition>
  );
}
