import { useState, type FormEvent, useEffect } from 'react';
import { User, Lock } from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
import { authService } from '../../services/auth';
import { handleApiError } from '../../services/api';
import { Card, CardHeader, CardTitle } from '../ui/Card';
import { Button } from '../ui/Button';
import { Input } from '../ui/Input';

interface AccountSettingsPanelProps {
  onToast?: (message: string) => void;
}

export function AccountSettingsPanel({ onToast }: AccountSettingsPanelProps) {
  const { user, updateAccountProfile } = useAuth();
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [saving, setSaving] = useState(false);

  const [oldPassword, setOldPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [newPasswordConfirm, setNewPasswordConfirm] = useState('');
  const [passwordSaving, setPasswordSaving] = useState(false);

  useEffect(() => {
    if (user) {
      setFirstName(user.first_name || '');
      setLastName(user.last_name || '');
      setEmail(user.email || '');
    }
  }, [user]);

  const handleSaveProfile = async (e: FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      await updateAccountProfile({
        first_name: firstName.trim(),
        last_name: lastName.trim(),
        email: email.trim(),
      });
      onToast?.('Account details saved.');
    } catch (err) {
      onToast?.(handleApiError(err));
    } finally {
      setSaving(false);
    }
  };

  const handleChangePassword = async (e: FormEvent) => {
    e.preventDefault();
    if (newPassword !== newPasswordConfirm) {
      onToast?.('New passwords do not match.');
      return;
    }
    setPasswordSaving(true);
    try {
      await authService.changePassword({
        old_password: oldPassword,
        new_password: newPassword,
        new_password_confirm: newPasswordConfirm,
      });
      setOldPassword('');
      setNewPassword('');
      setNewPasswordConfirm('');
      onToast?.('Password updated successfully.');
    } catch (err) {
      onToast?.(handleApiError(err));
    } finally {
      setPasswordSaving(false);
    }
  };

  if (!user) return null;

  return (
    <div className="space-y-6 max-w-xl">
      <div>
        <h1 className="text-2xl font-bold text-zinc-100">Profile</h1>
        <p className="text-sm text-zinc-500 mt-1">
          Update your account name and email. Your username stays the same for sign-in.
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle info="These details are stored on your Sync account and may be shown to brands or creators where relevant.">
            Account details
          </CardTitle>
        </CardHeader>
        <form onSubmit={handleSaveProfile} className="space-y-4">
          <Input
            label="Username"
            value={user.username}
            disabled
            readOnly
            icon={<User className="h-4 w-4" />}
            className="disabled:bg-gray-50 disabled:text-gray-600 disabled:cursor-not-allowed"
          />
          <Input
            label="First name"
            value={firstName}
            onChange={(e) => setFirstName(e.target.value)}
            required
            autoComplete="given-name"
          />
          <Input
            label="Last name"
            value={lastName}
            onChange={(e) => setLastName(e.target.value)}
            required
            autoComplete="family-name"
          />
          <Input
            label="Email"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            autoComplete="email"
          />
          <Button type="submit" loading={saving} icon={<User className="h-4 w-4" />}>
            Save changes
          </Button>
        </form>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Change password</CardTitle>
        </CardHeader>
        <form onSubmit={handleChangePassword} className="space-y-4">
          <Input
            label="Current password"
            type="password"
            value={oldPassword}
            onChange={(e) => setOldPassword(e.target.value)}
            required
            autoComplete="current-password"
          />
          <Input
            label="New password"
            type="password"
            value={newPassword}
            onChange={(e) => setNewPassword(e.target.value)}
            required
            autoComplete="new-password"
          />
          <Input
            label="Confirm new password"
            type="password"
            value={newPasswordConfirm}
            onChange={(e) => setNewPasswordConfirm(e.target.value)}
            required
            autoComplete="new-password"
          />
          <Button
            type="submit"
            variant="secondary"
            loading={passwordSaving}
            icon={<Lock className="h-4 w-4" />}
          >
            Update password
          </Button>
        </form>
      </Card>
    </div>
  );
}
