import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Shield, Lock, Eye, Trash2 } from 'lucide-react';
import { Card } from '../components/ui/Card';
import { Toggle } from '../components/ui/Toggle';
import { Button } from '../components/ui/Button';
import { GradientButton } from '../components/ui/GradientButton';
import { Modal } from '../components/ui/Modal';
import { Input } from '../components/ui/Input';
import { api } from '../api/client';
import { useAuth } from '../context/AuthContext';

interface Settings {
  showOnline: boolean;
  showRating: boolean;
  twoFactorEnabled: boolean;
  notifEmail: boolean;
  marketingEmail: boolean;
}

interface Session {
  id: string;
  userAgent: string | null;
  ipAddress: string | null;
  createdAt: string;
}

export function SettingsPage() {
  const navigate = useNavigate();
  const { logout } = useAuth();
  const [settings, setSettings] = useState<Settings>({
    showOnline: true,
    showRating: true,
    twoFactorEnabled: false,
    notifEmail: true,
    marketingEmail: false,
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  // Password modal
  const [showPassword, setShowPassword] = useState(false);
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const [passwordSuccess, setPasswordSuccess] = useState('');
  const [changingPassword, setChangingPassword] = useState(false);

  // Sessions modal
  const [showSessions, setShowSessions] = useState(false);
  const [sessions, setSessions] = useState<Session[]>([]);

  // Delete account modal
  const [showDelete, setShowDelete] = useState(false);
  const [deletePassword, setDeletePassword] = useState('');
  const [deleteError, setDeleteError] = useState('');
  const [deleting, setDeleting] = useState(false);

  // Blocked users modal
  const [showBlocked, setShowBlocked] = useState(false);

  useEffect(() => {
    api.get<Settings>('/users/settings')
      .then(setSettings)
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const handleSave = async () => {
    setSaving(true);
    try {
      const updated = await api.put<Settings>('/users/settings', {
        showOnline: settings.showOnline,
        showRating: settings.showRating,
        notifEmail: settings.notifEmail,
        marketingEmail: settings.marketingEmail,
      });
      setSettings(updated);
    } catch {}
    setSaving(false);
  };

  const update = (key: keyof Settings, value: boolean) => {
    setSettings(prev => ({ ...prev, [key]: value }));
  };

  const handleChangePassword = async () => {
    setPasswordError('');
    setPasswordSuccess('');
    if (newPassword.length < 8) {
      setPasswordError('New password must be at least 8 characters');
      return;
    }
    setChangingPassword(true);
    try {
      await api.put('/users/password', { currentPassword, newPassword });
      setPasswordSuccess('Password updated successfully');
      setCurrentPassword('');
      setNewPassword('');
    } catch (err) {
      setPasswordError(err instanceof Error ? err.message : 'Failed to change password');
    }
    setChangingPassword(false);
  };

  const handleViewSessions = async () => {
    try {
      const data = await api.get<Session[]>('/users/sessions');
      setSessions(data);
      setShowSessions(true);
    } catch {}
  };

  const handleDeleteAccount = async () => {
    setDeleteError('');
    setDeleting(true);
    try {
      await api.delete('/users/account', { password: deletePassword });
      logout();
      navigate('/');
    } catch (err) {
      setDeleteError(err instanceof Error ? err.message : 'Failed to delete account');
    }
    setDeleting(false);
  };

  if (loading) return <div className="text-center text-gray-500 py-12">Loading settings...</div>;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">Privacy & Security Settings</h1>
        <p className="text-sm text-gray-500 mt-1">Manage your privacy, security and data preferences</p>
      </div>

      <Card>
        <div className="flex items-center gap-3 mb-4">
          <div className="w-8 h-8 rounded-lg bg-primary-50 flex items-center justify-center">
            <Eye className="w-4 h-4 text-primary-500" />
          </div>
          <h2 className="font-semibold text-gray-900">Account Privacy</h2>
        </div>
        <div className="space-y-4">
          <Toggle checked={settings.showOnline} onChange={(v) => update('showOnline', v)} label="Show Online Status" description="Let others see when you're online" />
          <Toggle checked={settings.showRating} onChange={(v) => update('showRating', v)} label="Show Seller Rating" description="Display your rating on your profile" />
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm font-medium text-gray-700">Blocked Users</div>
              <div className="text-xs text-gray-500">Manage your blocked users list</div>
            </div>
            <Button variant="outline" size="sm" onClick={() => setShowBlocked(true)}>Manage</Button>
          </div>
        </div>
      </Card>

      <Card>
        <div className="flex items-center gap-3 mb-4">
          <div className="w-8 h-8 rounded-lg bg-primary-50 flex items-center justify-center">
            <Shield className="w-4 h-4 text-primary-500" />
          </div>
          <h2 className="font-semibold text-gray-900">Security Settings</h2>
        </div>
        <div className="space-y-4">
          <Toggle checked={settings.twoFactorEnabled} onChange={(v) => update('twoFactorEnabled', v)} label="Two-Factor Authentication" description="Add an extra layer of security" />
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm font-medium text-gray-700">Password Reset</div>
              <div className="text-xs text-gray-500">Change your account password</div>
            </div>
            <Button variant="outline" size="sm" onClick={() => { setShowPassword(true); setPasswordError(''); setPasswordSuccess(''); }}>Change</Button>
          </div>
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm font-medium text-gray-700">Login Activity</div>
              <div className="text-xs text-gray-500">View your recent login activity</div>
            </div>
            <Button variant="outline" size="sm" onClick={handleViewSessions}>View</Button>
          </div>
        </div>
      </Card>

      <Card>
        <div className="flex items-center gap-3 mb-4">
          <div className="w-8 h-8 rounded-lg bg-primary-50 flex items-center justify-center">
            <Lock className="w-4 h-4 text-primary-500" />
          </div>
          <h2 className="font-semibold text-gray-900">Data & Privacy</h2>
        </div>
        <div className="space-y-4">
          <Toggle checked={settings.notifEmail} onChange={(v) => update('notifEmail', v)} label="Notification Emails" description="Receive email notifications" />
          <Toggle checked={settings.marketingEmail} onChange={(v) => update('marketingEmail', v)} label="Marketing Emails" description="Receive promotional emails" />
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm font-medium text-gray-700">Privacy Policy</div>
              <div className="text-xs text-gray-500">Read our privacy policy</div>
            </div>
            <a href="/privacy" target="_blank" className="text-sm text-primary-600 hover:text-primary-700 font-medium">View</a>
          </div>
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm font-medium text-gray-700">Terms of Service</div>
              <div className="text-xs text-gray-500">Read our terms of service</div>
            </div>
            <a href="/terms" target="_blank" className="text-sm text-primary-600 hover:text-primary-700 font-medium">View</a>
          </div>
        </div>
      </Card>

      <div className="flex items-center justify-between pt-4">
        <Button variant="danger" size="md" onClick={() => { setShowDelete(true); setDeleteError(''); setDeletePassword(''); }}>
          <Trash2 className="w-4 h-4 mr-2" /> Delete Account
        </Button>
        <GradientButton size="md" onClick={handleSave} disabled={saving}>
          {saving ? 'Saving...' : 'Save Settings'}
        </GradientButton>
      </div>

      {/* Change Password Modal */}
      <Modal isOpen={showPassword} onClose={() => setShowPassword(false)} title="Change Password" size="sm">
        {passwordError && <p className="text-sm text-red-500 mb-3">{passwordError}</p>}
        {passwordSuccess && <p className="text-sm text-green-600 mb-3">{passwordSuccess}</p>}
        <div className="space-y-4 mb-6">
          <Input label="Current Password" type="password" value={currentPassword} onChange={(e) => setCurrentPassword(e.target.value)} placeholder="Enter current password" />
          <Input label="New Password" type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} placeholder="Enter new password (min 8 chars)" />
        </div>
        <div className="flex gap-3">
          <Button variant="secondary" className="flex-1" onClick={() => setShowPassword(false)}>Cancel</Button>
          <GradientButton className="flex-1" onClick={handleChangePassword} disabled={changingPassword}>
            {changingPassword ? 'Changing...' : 'Change Password'}
          </GradientButton>
        </div>
      </Modal>

      {/* Login Activity Modal */}
      <Modal isOpen={showSessions} onClose={() => setShowSessions(false)} title="Login Activity" size="md">
        {sessions.length === 0 ? (
          <p className="text-sm text-gray-500">No sessions found.</p>
        ) : (
          <div className="space-y-3">
            {sessions.map(s => (
              <div key={s.id} className="p-3 bg-gray-50 rounded-xl text-sm">
                <p className="font-medium text-gray-900 truncate">{s.userAgent || 'Unknown device'}</p>
                <div className="flex gap-4 mt-1 text-xs text-gray-500">
                  <span>IP: {s.ipAddress || 'Unknown'}</span>
                  <span>{new Date(s.createdAt).toLocaleString()}</span>
                </div>
              </div>
            ))}
          </div>
        )}
      </Modal>

      {/* Delete Account Modal */}
      <Modal isOpen={showDelete} onClose={() => setShowDelete(false)} title="Delete Account" size="sm">
        <p className="text-sm text-gray-500 mb-4">This action cannot be undone. Enter your password to confirm.</p>
        {deleteError && <p className="text-sm text-red-500 mb-3">{deleteError}</p>}
        <div className="mb-6">
          <Input label="Password" type="password" value={deletePassword} onChange={(e) => setDeletePassword(e.target.value)} placeholder="Enter your password" />
        </div>
        <div className="flex gap-3">
          <Button variant="secondary" className="flex-1" onClick={() => setShowDelete(false)}>Cancel</Button>
          <Button variant="danger" className="flex-1" onClick={handleDeleteAccount} disabled={deleting}>
            {deleting ? 'Deleting...' : 'Delete Account'}
          </Button>
        </div>
      </Modal>

      {/* Blocked Users Modal */}
      <Modal isOpen={showBlocked} onClose={() => setShowBlocked(false)} title="Blocked Users" size="sm">
        <p className="text-sm text-gray-500">You can block users from their profile page or listing page. Blocked users cannot see your listings or message you.</p>
      </Modal>
    </div>
  );
}
