import React, { useState, useEffect } from 'react';
import toast from 'react-hot-toast';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/context/AuthContext';
import { useTheme } from '@/context/ThemeContext';
import { authApi, backupApi, exportApi, userApi } from '@/services/api';
import type { User } from '@/types';

const CURRENCIES = ['PKR', 'USD', 'EUR', 'GBP', 'INR'];
const TIMEZONES = [
    'Asia/Karachi', 'Asia/Dubai', 'Asia/Kolkata',
    'America/New_York', 'Europe/London', 'Europe/Berlin', 'Australia/Sydney',
];

export default function Settings() {
    const { user, logout, updateUser } = useAuth();
    const { theme, setTheme } = useTheme();
    const navigate = useNavigate();

    const [name, setName] = useState(user?.name || '');
    const [currency, setCurrency] = useState(user?.currency || 'PKR');
    const [timezone, setTimezone] = useState(user?.timezone || 'Asia/Karachi');
    const [autoBackup, setAutoBackup] = useState(user?.auto_backup || false);
    const [saving, setSaving] = useState(false);
    const [savingAutoBackup, setSavingAutoBackup] = useState(false);
    const [backupStatus, setBackupStatus] = useState<any>(null);
    const [backingUp, setBackingUp] = useState(false);
    const [users, setUsers] = useState<any[]>([]);
    const [showAddUser, setShowAddUser] = useState(false);
    const [newUserName, setNewUserName] = useState('');
    const [newUserEmail, setNewUserEmail] = useState('');
    const [newUserPassword, setNewUserPassword] = useState('');
    const [savingUser, setSavingUser] = useState(false);
    const [showPasswordForm, setShowPasswordForm] = useState(false);
    const [currentPassword, setCurrentPassword] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [confirmNewPassword, setConfirmNewPassword] = useState('');
    const [changingPassword, setChangingPassword] = useState(false);

    useEffect(() => {
        if (user?.is_admin) {
            userApi.getAll().then(res => setUsers(res.data)).catch(() => {});
        }
        backupApi.status().then(res => setBackupStatus(res.data)).catch(() => {});
    }, [user]);

    const handleSaveProfile = async () => {
        setSaving(true);
        try {
            const res = await authApi.updateProfile({ name, currency, timezone, auto_backup });
            updateUser(res.data.user);
            toast.success('Profile saved');
        } catch (err: any) {
            toast.error(err.response?.data?.message || 'Failed to save');
        } finally {
            setSaving(false);
        }
    };

    const handleToggleAutoBackup = async () => {
        const newValue = !autoBackup;
        setAutoBackup(newValue);
        setSavingAutoBackup(true);
        try {
            const res = await authApi.updateProfile({ name, currency, timezone, auto_backup: newValue });
            updateUser(res.data.user);
        } catch (err: any) {
            setAutoBackup(!newValue);
            toast.error(err.response?.data?.message || 'Failed to update auto backup');
        } finally {
            setSavingAutoBackup(false);
        }
    };

    const handleBackupNow = async () => {
        setBackingUp(true);
        try {
            const res = await backupApi.run();
            setBackupStatus(res.data);
            toast.success('Backup created successfully!');
        } catch (err: any) {
            toast.error(err.response?.data?.message || 'Backup failed');
        } finally {
            setBackingUp(false);
        }
    };

    const handleDownloadBackup = async () => {
        try {
            const res = await backupApi.download();
            const url = URL.createObjectURL(new Blob([res.data]));
            const a = document.createElement('a');
            a.href = url;
            a.download = 'backup.zip';
            a.click();
            URL.revokeObjectURL(url);
        } catch {
            toast.error('No backup available');
        }
    };

    const handleExport = async () => {
        try {
            const res = await exportApi.expenses();
            const url = URL.createObjectURL(new Blob([res.data]));
            const a = document.createElement('a');
            a.href = url;
            a.download = 'all-expenses.csv';
            a.click();
            URL.revokeObjectURL(url);
        } catch {
            toast.error('Export failed');
        }
    };

    const handleAddUser = async () => {
        if (!newUserName || !newUserEmail || !newUserPassword) return;
        setSavingUser(true);
        try {
            await userApi.create({ name: newUserName, email: newUserEmail, password: newUserPassword });
            const res = await userApi.getAll();
            setUsers(res.data);
            setShowAddUser(false);
            setNewUserName('');
            setNewUserEmail('');
            setNewUserPassword('');
            toast.success('User added');
        } catch (err: any) {
            toast.error(err.response?.data?.message || 'Failed to add user');
        } finally {
            setSavingUser(false);
        }
    };

    const handleDeleteUser = async (id: number) => {
        if (!confirm('Delete this user? Their expenses will also be deleted.')) return;
        try {
            await userApi.delete(id);
            setUsers(prev => prev.filter(u => u.id !== id));
            toast.success('User deleted');
        } catch (err: any) {
            toast.error(err.response?.data?.message || 'Failed to delete user');
        }
    };

    const handleLogout = async () => {
        await logout();
        navigate('/login');
    };

    const handleChangePassword = async () => {
        if (!currentPassword || !newPassword || newPassword !== confirmNewPassword) {
            toast.error('Passwords do not match');
            return;
        }
        if (newPassword.length < 8) {
            toast.error('Password must be at least 8 characters');
            return;
        }
        setChangingPassword(true);
        try {
            await authApi.changePassword(currentPassword, newPassword, confirmNewPassword);
            toast.success('Password changed successfully');
            setShowPasswordForm(false);
            setCurrentPassword('');
            setNewPassword('');
            setConfirmNewPassword('');
        } catch (err: any) {
            toast.error(err.response?.data?.message || 'Failed to change password');
        } finally {
            setChangingPassword(false);
        }
    };

    const Section = ({ title, icon, children }: { title: string; icon?: string; children: React.ReactNode }) => (
        <div className="bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm rounded-2xl border border-gray-100/50 dark:border-gray-700/30 overflow-hidden">
            <div className="px-5 py-3.5 border-b border-gray-50 dark:border-gray-700/20">
                <h2 className="text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">{icon} {title}</h2>
            </div>
            <div className="p-5">
                {children}
            </div>
        </div>
    );

    return (
        <div className="max-w-2xl mx-auto space-y-6">
            <div>
                <h1 className="text-3xl lg:text-4xl font-bold text-gray-900 dark:text-gray-100 tracking-tight">Settings</h1>
                <p className="text-gray-400 dark:text-gray-500 text-sm mt-1">System preferences</p>
            </div>

            <Section title="Profile" icon="👤">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-600 dark:text-gray-400 mb-1">Name</label>
                        <input type="text" value={name} onChange={e => setName(e.target.value)} className="input-field" />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-600 dark:text-gray-400 mb-1">Email</label>
                        <input type="email" value={user?.email || ''} disabled className="input-field bg-gray-50/50 dark:bg-gray-700/50" />
                    </div>
                </div>
                <div className="flex flex-wrap gap-2">
                    <button onClick={handleSaveProfile} disabled={saving} className="btn-primary">
                        {saving ? 'Saving...' : 'Save Profile'}
                    </button>
                    <button onClick={() => setShowPasswordForm(!showPasswordForm)} className="btn-ghost">
                        🔑 Change Password
                    </button>
                </div>
                {showPasswordForm && (
                    <div className="mt-4 space-y-3 border-t border-gray-100 dark:border-gray-700/30 pt-4">
                        <input type="password" value={currentPassword} onChange={e => setCurrentPassword(e.target.value)} placeholder="Current password" className="input-field" />
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                            <input type="password" value={newPassword} onChange={e => setNewPassword(e.target.value)} placeholder="New password (min 8 chars)" className="input-field" />
                            <input type="password" value={confirmNewPassword} onChange={e => setConfirmNewPassword(e.target.value)} placeholder="Confirm new password" className="input-field" />
                        </div>
                        <button onClick={handleChangePassword} disabled={changingPassword} className="btn-primary w-full">
                            {changingPassword ? 'Changing...' : 'Update Password'}
                        </button>
                    </div>
                )}
            </Section>

            <Section title="Preferences" icon="🎨">
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-600 dark:text-gray-400 mb-2">Theme</label>
                        <div className="flex gap-2">
                            {(['light', 'dark', 'system'] as const).map(t => (
                                <button key={t} onClick={() => setTheme(t)} className={`flex-1 py-2.5 rounded-xl text-sm font-medium capitalize transition-all ${theme === t ? 'bg-teal-50 dark:bg-teal-900/30 ring-2 ring-teal-500/50 text-teal-700 dark:text-teal-300' : 'bg-gray-50 dark:bg-gray-700/50 text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700'}`}>
                                    {t === 'light' ? '☀️' : t === 'dark' ? '🌙' : '💻'}
                                </button>
                            ))}
                        </div>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-600 dark:text-gray-400 mb-1">Currency</label>
                        <select value={currency} onChange={e => setCurrency(e.target.value)} className="input-field">
                            {CURRENCIES.map(c => <option key={c} value={c}>{c}</option>)}
                        </select>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-600 dark:text-gray-400 mb-1">Timezone</label>
                        <select value={timezone} onChange={e => setTimezone(e.target.value)} className="input-field">
                            {TIMEZONES.map(t => <option key={t} value={t}>{t}</option>)}
                        </select>
                    </div>
                </div>
            </Section>

            <Section title="Backup & Data" icon="💾">
                <div className="flex items-center justify-between mb-5">
                    <div>
                        <p className="text-sm font-medium text-gray-700 dark:text-gray-200">Auto Backup on Logout</p>
                        <p className="text-xs text-gray-400 mt-0.5">Backup database + receipts on logout</p>
                    </div>
                    <button onClick={handleToggleAutoBackup} disabled={savingAutoBackup} className={`w-12 h-6 rounded-full transition-colors relative flex-shrink-0 ${autoBackup ? 'bg-teal-600' : 'bg-gray-300 dark:bg-gray-600'} ${savingAutoBackup ? 'opacity-50 cursor-not-allowed' : ''}`}>
                        <div className={`w-5 h-5 bg-white rounded-full shadow absolute top-0.5 transition-all duration-200 ${autoBackup ? 'left-6' : 'left-0.5'}`} />
                    </button>
                </div>
                <div className="flex flex-wrap gap-2">
                    <button onClick={handleBackupNow} disabled={backingUp} className="btn-primary text-sm">
                        {backingUp ? 'Backing up...' : '📦 Backup Now'}
                    </button>
                    {backupStatus?.exists && (
                        <button onClick={handleDownloadBackup} className="btn-ghost text-sm">⬇️ Download ({Math.round(backupStatus.size / 1024)}KB)</button>
                    )}
                    <button onClick={handleExport} className="btn-ghost text-sm">📄 Export CSV</button>
                </div>
                {backupStatus?.exists && <p className="text-xs text-gray-400 mt-3">Latest backup: {backupStatus.date}</p>}
            </Section>

            {user?.is_admin && (
                <Section title="User Management" icon="👥">
                    {users.length > 0 && (
                        <div className="space-y-1 mb-4">
                            {users.map(u => (
                                <div key={u.id} className="flex items-center justify-between py-2 px-3 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-700/20 transition-colors">
                                    <div>
                                        <p className="text-sm font-medium text-gray-700 dark:text-gray-200">{u.name}</p>
                                        <p className="text-xs text-gray-400">{u.email}</p>
                                    </div>
                                    <button onClick={() => handleDeleteUser(u.id)} className="text-xs text-red-400 hover:text-red-600 px-3 py-1.5 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-all">Remove</button>
                                </div>
                            ))}
                        </div>
                    )}
                    {showAddUser ? (
                        <div className="space-y-3">
                            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                                <input type="text" value={newUserName} onChange={e => setNewUserName(e.target.value)} placeholder="Name" className="input-field" />
                                <input type="email" value={newUserEmail} onChange={e => setNewUserEmail(e.target.value)} placeholder="Email" className="input-field" />
                                <input type="password" value={newUserPassword} onChange={e => setNewUserPassword(e.target.value)} placeholder="Password" className="input-field" />
                            </div>
                            <div className="flex gap-2">
                                <button onClick={() => setShowAddUser(false)} className="btn-ghost flex-1">Cancel</button>
                                <button onClick={handleAddUser} disabled={savingUser} className="btn-primary flex-1">
                                    {savingUser ? 'Adding...' : 'Add User'}
                                </button>
                            </div>
                        </div>
                    ) : (
                        <button onClick={() => setShowAddUser(true)} className="btn-ghost w-full">+ Add Family Member</button>
                    )}
                </Section>
            )}

            <button onClick={handleLogout} className="w-full py-3 text-sm font-medium text-red-400 hover:text-red-500 bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm rounded-2xl border border-red-100 dark:border-red-900/30 hover:bg-red-50 dark:hover:bg-red-900/20 transition-all active:scale-[0.98]">
                🚪 Logout
            </button>
        </div>
    );
}
