import { useState, useEffect, useRef } from 'react';
import { UserCircle, AlertCircle, CheckCircle, Loader2, Eye, EyeOff, Pencil, X, KeyRound } from 'lucide-react';
import { DEFAULT_LOCALE } from '@archer/domain';
import { PageLayout } from '@/components/shared';
import { useProfile, useUpdateProfile, useChangePassword, useResendVerification } from './hooks/useProfile';
import type { ProfileFormData } from '@/infrastructure/http/api/profile';
import { useTranslation } from '@/i18n/TranslationProvider';
import { PersonalAddressSection } from './PersonalAddressSection';
import { BillingCurrencySection } from './BillingCurrencySection';

export function ProfilePage() {
  const { t } = useTranslation();
  const { data: profile, isLoading, error } = useProfile();
  const updateMutation = useUpdateProfile();
  const passwordMutation = useChangePassword();
  const resendMutation = useResendVerification();

  const [editing, setEditing] = useState(false);
  const [formData, setFormData] = useState<ProfileFormData>({
    firstName: '',
    lastName: '',
    phone: '',
    locale: DEFAULT_LOCALE,
    timezone: 'Europe/Berlin',
  });

  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPasswords, setShowPasswords] = useState(false);
  const [passwordError, setPasswordError] = useState('');

  const passwordRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (profile) {
      setFormData(profile.toFormData());
    }
  }, [profile]);

  const handleChange = (field: keyof ProfileFormData, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const handleProfileSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    updateMutation.mutate(formData, {
      onSuccess: () => setEditing(false),
    });
  };

  const handleCancelEdit = () => {
    if (profile) setFormData(profile.toFormData());
    setEditing(false);
  };

  const scrollToPassword = () => {
    passwordRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  const handlePasswordSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setPasswordError('');

    if (newPassword.length < 8) {
      setPasswordError(t('profile.passwordMinLength'));
      return;
    }
    if (newPassword !== confirmPassword) {
      setPasswordError(t('profile.passwordsNoMatch'));
      return;
    }

    passwordMutation.mutate(
      { currentPassword, newPassword },
      {
        onSuccess: () => {
          setCurrentPassword('');
          setNewPassword('');
          setConfirmPassword('');
        },
      },
    );
  };

  return (
    <PageLayout
      title={t('profile.title')}
      subtitle={t('profile.subtitle')}
      icon={<UserCircle size={24} />}
      gradient={true}
    >
        {error && (
          <div className="bg-destructive/10 border border-destructive/20 rounded-lg p-4">
            <p className="text-sm text-destructive">{t('profile.errorLoading', { error: (error as Error).message })}</p>
          </div>
        )}

        {profile?.emailNotVerified && (
          <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 flex items-center justify-between gap-4">
            <div className="flex items-center gap-3">
              <AlertCircle className="h-5 w-5 text-yellow-600 flex-shrink-0" />
              <p className="text-sm text-yellow-800">{t('profile.emailNotVerified')}</p>
            </div>
            <button
              onClick={() => resendMutation.mutate()}
              disabled={resendMutation.isPending}
              className="flex-shrink-0 text-sm font-medium text-yellow-700 hover:text-yellow-900 disabled:opacity-50"
            >
              {resendMutation.isPending ? t('profile.sending') : t('profile.resend')}
            </button>
          </div>
        )}

        {/* Personal Information */}
        <div className="bg-card rounded-xl border border-border p-6 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-foreground">{t('profile.personalInfo')}</h2>
            {!editing && !isLoading && (
              <button
                onClick={() => setEditing(true)}
                className="flex items-center gap-1.5 text-sm font-medium text-primary hover:text-primary/80 transition-colors"
              >
                <Pencil className="h-4 w-4" />
                {t('common.edit')}
              </button>
            )}
          </div>

          {isLoading ? (
            <div className="space-y-4">
              {[1, 2, 3, 4].map((i) => (
                <div key={i} className="h-6 bg-muted animate-pulse rounded w-48" />
              ))}
            </div>
          ) : editing ? (
            <form onSubmit={handleProfileSubmit} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">{t('profile.firstName')}</label>
                  <input
                    type="text"
                    value={formData.firstName}
                    onChange={(e) => handleChange('firstName', e.target.value)}
                    className="w-full px-3 py-2.5 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50"
                    autoFocus
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">{t('profile.lastName')}</label>
                  <input
                    type="text"
                    value={formData.lastName}
                    onChange={(e) => handleChange('lastName', e.target.value)}
                    className="w-full px-3 py-2.5 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-foreground mb-1">{t('profile.email')}</label>
                <div className="flex items-center gap-2">
                  <input
                    type="email"
                    value={profile?.email || ''}
                    disabled
                    className="flex-1 px-3 py-2.5 border border-border rounded-lg bg-muted text-muted-foreground"
                  />
                  {profile?.emailVerified && (
                    <CheckCircle className="h-5 w-5 text-green-500 flex-shrink-0" />
                  )}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-foreground mb-1">{t('profile.phone')}</label>
                <input
                  type="tel"
                  value={formData.phone}
                  onChange={(e) => handleChange('phone', e.target.value)}
                  placeholder={t('profile.phonePlaceholder')}
                  className="w-full px-3 py-2.5 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50"
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">{t('profile.language')}</label>
                  <select
                    value={formData.locale}
                    onChange={(e) => handleChange('locale', e.target.value)}
                    className="w-full px-3 py-2.5 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50"
                  >
                    <option value="de">Deutsch</option>
                    <option value="en">English</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">{t('profile.timezone')}</label>
                  <select
                    value={formData.timezone}
                    onChange={(e) => handleChange('timezone', e.target.value)}
                    className="w-full px-3 py-2.5 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50"
                  >
                    <option value="Europe/Berlin">Europe/Berlin</option>
                    <option value="Europe/London">Europe/London</option>
                    <option value="Europe/Paris">Europe/Paris</option>
                    <option value="America/New_York">America/New York</option>
                    <option value="America/Los_Angeles">America/Los Angeles</option>
                    <option value="Asia/Tokyo">Asia/Tokyo</option>
                  </select>
                </div>
              </div>

              <div className="flex items-center gap-3 pt-2">
                <button
                  type="submit"
                  disabled={updateMutation.isPending}
                  className="bg-primary text-primary-foreground px-6 py-2.5 rounded-lg font-medium hover:bg-primary/90 disabled:opacity-50 transition-colors flex items-center gap-2"
                >
                  {updateMutation.isPending && <Loader2 className="h-4 w-4 animate-spin" />}
                  {t('common.save')}
                </button>
                <button
                  type="button"
                  onClick={handleCancelEdit}
                  className="flex items-center gap-1.5 px-4 py-2.5 rounded-lg text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
                >
                  <X className="h-4 w-4" />
                  {t('common.cancel')}
                </button>
                {updateMutation.isError && (
                  <span className="text-sm text-destructive">
                    {(updateMutation.error as Error).message || t('profile.updateFailed')}
                  </span>
                )}
              </div>
            </form>
          ) : (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-muted-foreground">{t('profile.firstName')}</p>
                  <p className="text-sm font-medium text-foreground mt-0.5">{profile?.firstName || '-'}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">{t('profile.lastName')}</p>
                  <p className="text-sm font-medium text-foreground mt-0.5">{profile?.lastName || '-'}</p>
                </div>
              </div>

              <div>
                <p className="text-sm text-muted-foreground">{t('profile.email')}</p>
                <div className="flex items-center gap-2 mt-0.5 flex-wrap">
                  <p className="text-sm font-medium text-foreground">{profile?.email || '-'}</p>
                  {profile?.emailVerified ? (
                    <CheckCircle className="h-4 w-4 text-green-500" />
                  ) : (
                    <>
                      <span className="inline-flex items-center gap-1 text-xs font-medium text-amber-700 bg-amber-50 border border-amber-200 rounded px-2 py-0.5">
                        <AlertCircle className="h-3.5 w-3.5" />
                        {t('profile.emailNotVerified')}
                      </span>
                      <button
                        type="button"
                        onClick={() => resendMutation.mutate()}
                        disabled={resendMutation.isPending || resendMutation.isSuccess}
                        className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:text-primary/80 disabled:opacity-50 transition-colors"
                      >
                        {resendMutation.isPending && <Loader2 className="h-3 w-3 animate-spin" />}
                        {resendMutation.isSuccess
                          ? t('profile.verificationSent')
                          : resendMutation.isPending
                            ? t('profile.sending')
                            : t('profile.resend')}
                      </button>
                      {resendMutation.isError && (
                        <span className="text-xs text-destructive">
                          {(resendMutation.error as Error).message || t('profile.updateFailed')}
                        </span>
                      )}
                    </>
                  )}
                </div>
              </div>

              <div>
                <p className="text-sm text-muted-foreground">{t('profile.phone')}</p>
                <p className="text-sm font-medium text-foreground mt-0.5">{profile?.phone || '-'}</p>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-muted-foreground">{t('profile.language')}</p>
                  <p className="text-sm font-medium text-foreground mt-0.5">{profile?.localeLabel}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">{t('profile.timezone')}</p>
                  <p className="text-sm font-medium text-foreground mt-0.5">{profile?.timezone || '-'}</p>
                </div>
              </div>

              <div className="pt-2">
                <button
                  onClick={scrollToPassword}
                  className="flex items-center gap-1.5 text-sm font-medium text-primary hover:text-primary/80 transition-colors"
                >
                  <KeyRound className="h-4 w-4" />
                  {t('profile.changePasswordLink')}
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Billing Address (PERSONAL accounts only — business users edit on /dashboard/company) */}
        {profile?.isPersonal && <PersonalAddressSection />}

        {/* Billing currency — PERSONAL accounts only; BUSINESS see it on /dashboard/company */}
        {profile?.isPersonal && <BillingCurrencySection />}

        {/* Change Password */}
        <div ref={passwordRef} className="bg-card rounded-xl border border-border p-6 shadow-sm">
          <h2 className="text-lg font-semibold text-foreground mb-4">{t('profile.changePasswordTitle')}</h2>
          <form onSubmit={handlePasswordSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">{t('profile.currentPassword')}</label>
              <div className="relative">
                <input
                  type={showPasswords ? 'text' : 'password'}
                  value={currentPassword}
                  onChange={(e) => setCurrentPassword(e.target.value)}
                  required
                  className="w-full px-3 py-2.5 pr-10 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50"
                />
                <button
                  type="button"
                  onClick={() => setShowPasswords(!showPasswords)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                >
                  {showPasswords ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">{t('profile.newPassword')}</label>
              <input
                type={showPasswords ? 'text' : 'password'}
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                required
                placeholder={t('profile.newPasswordPlaceholder')}
                className="w-full px-3 py-2.5 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">{t('profile.confirmNewPassword')}</label>
              <input
                type={showPasswords ? 'text' : 'password'}
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                required
                className="w-full px-3 py-2.5 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50"
              />
            </div>

            {(passwordError || passwordMutation.isError) && (
              <p className="text-sm text-destructive">
                {passwordError || (passwordMutation.error as Error).message || t('profile.passwordChangeFailed')}
              </p>
            )}

            <div className="flex items-center gap-3 pt-2">
              <button
                type="submit"
                disabled={passwordMutation.isPending}
                className="bg-primary text-primary-foreground px-6 py-2.5 rounded-lg font-medium hover:bg-primary/90 disabled:opacity-50 transition-colors flex items-center gap-2"
              >
                {passwordMutation.isPending && <Loader2 className="h-4 w-4 animate-spin" />}
                {t('profile.changePasswordButton')}
              </button>
              {passwordMutation.isSuccess && (
                <span className="text-sm text-green-600">{t('profile.passwordChanged')}</span>
              )}
            </div>
          </form>
        </div>
    </PageLayout>
  );
}
