import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '@/store/authStore';
import { useUpdateUser } from '@/api/hooks';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { Avatar } from '@/components/ui/Avatar';
import { useToast } from '@/components/ui/Toast';

export function SettingsProfilePage() {
  const { t } = useTranslation();
  const toast = useToast();
  const { user } = useAuthStore();
  const updateUserMutation = useUpdateUser();

  const [firstName, setFirstName] = useState(user?.first_name || '');
  const [lastName, setLastName] = useState(user?.last_name || '');
  const [email, setEmail] = useState(user?.email || '');
  const [avatarUrl, setAvatarUrl] = useState(user?.avatar_url || '');
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [profileDirty, setProfileDirty] = useState(false);
  const [passwordDirty, setPasswordDirty] = useState(false);

  const handleProfileSave = async () => {
    if (!user) return;
    try {
      await updateUserMutation.mutateAsync({
        id: user.id,
        data: { first_name: firstName, last_name: lastName, email, avatar_url: avatarUrl || null },
      });
      toast.success(t('settings.profileSaved'));
      setProfileDirty(false);
    } catch (err: any) {
      toast.error(err.message || t('common.error'));
    }
  };

  const handlePasswordChange = async () => {
    if (!user) return;
    if (newPassword !== confirmPassword) {
      toast.error(t('validation.passwordMismatch'));
      return;
    }
    if (newPassword.length < 8) {
      toast.error(t('auth.passwordTooShort'));
      return;
    }
    try {
      await updateUserMutation.mutateAsync({
        id: user.id,
        data: { current_password: currentPassword, new_password: newPassword },
      });
      toast.success(t('settings.passwordChanged'));
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
      setPasswordDirty(false);
    } catch (err: any) {
      toast.error(err.message || t('common.error'));
    }
  };

  const handleAvatarUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (event) => {
      setAvatarUrl(event.target?.result as string);
      setProfileDirty(true);
    };
    reader.readAsDataURL(file);
  };

  return (
    <div className="p-6 max-w-4xl mx-auto" data-testid="settings-profile-page">
      <h1 className="text-2xl font-bold text-secondary-900 mb-6">{t('settings.profile')}</h1>

      <div className="space-y-6">
        <Card title={t('settings.avatar')}>
          <div className="flex items-center gap-4">
            <Avatar name={`${firstName} ${lastName}`} src={avatarUrl || undefined} size="lg" />
            <div>
              <input
                type="file"
                accept="image/*"
                onChange={handleAvatarUpload}
                className="text-sm text-secondary-700 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-medium file:bg-primary-50 file:text-primary-700 hover:file:bg-primary-100 min-h-touch"
                aria-label={t('settings.avatar')}
                data-testid="avatar-upload"
              />
              {avatarUrl && (
                <button
                  onClick={() => { setAvatarUrl(''); setProfileDirty(true); }}
                  className="mt-2 text-sm text-danger-600 hover:text-danger-700"
                >
                  {t('common.delete')}
                </button>
              )}
            </div>
          </div>
        </Card>

        <Card title={t('settings.name')}>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Input
              label={t('settings.firstName')}
              value={firstName}
              onChange={(e) => { setFirstName(e.target.value); setProfileDirty(true); }}
              data-testid="profile-first-name"
            />
            <Input
              label={t('settings.lastName')}
              value={lastName}
              onChange={(e) => { setLastName(e.target.value); setProfileDirty(true); }}
              data-testid="profile-last-name"
            />
          </div>
          <div className="mt-4">
            <Input
              label={t('settings.email')}
              type="email"
              value={email}
              onChange={(e) => { setEmail(e.target.value); setProfileDirty(true); }}
              data-testid="profile-email"
            />
          </div>
          <div className="mt-4 flex justify-end">
            <Button
              onClick={handleProfileSave}
              disabled={!profileDirty}
              isLoading={updateUserMutation.isPending}
              data-testid="profile-save-btn"
            >
              {t('common.save')}
            </Button>
          </div>
        </Card>

        <Card title={t('settings.changePassword')}>
          <div className="space-y-4">
            <Input
              label={t('settings.currentPassword')}
              type="password"
              value={currentPassword}
              onChange={(e) => { setCurrentPassword(e.target.value); setPasswordDirty(true); }}
              data-testid="current-password"
            />
            <Input
              label={t('settings.newPassword')}
              type="password"
              value={newPassword}
              onChange={(e) => { setNewPassword(e.target.value); setPasswordDirty(true); }}
              data-testid="new-password"
            />
            <Input
              label={t('settings.confirmPassword')}
              type="password"
              value={confirmPassword}
              onChange={(e) => { setConfirmPassword(e.target.value); setPasswordDirty(true); }}
              error={confirmPassword && newPassword !== confirmPassword ? t('validation.passwordMismatch') : undefined}
              data-testid="confirm-password"
            />
            <div className="flex justify-end">
              <Button
                onClick={handlePasswordChange}
                disabled={!passwordDirty || !newPassword || !confirmPassword}
                isLoading={updateUserMutation.isPending}
                data-testid="password-change-btn"
              >
                {t('settings.changePassword')}
              </Button>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
}
