'use client';

/**
 * ============================================
 * ACCOUNT PROFILE PAGE
 * ============================================
 * Equivalent to: account/profile.html.twig in Shopware
 * Three sections: Personal info, Email change, Password change
 */

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth-context';
import AccountNav from '@/components/layout/AccountNav';
import {
  updateProfile,
  changeEmail,
  changePassword,
  getSalutations,
  Salutation,
} from '@/lib/shopware-api';

type Section = 'profile' | 'email' | 'password';

export default function ProfilePage() {
  const { customer, isLoggedIn, isLoading, refreshCustomer } = useAuth();
  const router = useRouter();
  const [salutations, setSalutations] = useState<Salutation[]>([]);
  const [activeSection, setActiveSection] = useState<Section>('profile');

  // Form states
  const [profileForm, setProfileForm] = useState({ salutationId: '', firstName: '', lastName: '' });
  const [emailForm, setEmailForm] = useState({ email: '', emailConfirmation: '', password: '' });
  const [passwordForm, setPasswordForm] = useState({ password: '', newPassword: '', newPasswordConfirm: '' });

  const [profileStatus, setProfileStatus] = useState<{ ok?: boolean; msg?: string }>({});
  const [emailStatus, setEmailStatus] = useState<{ ok?: boolean; msg?: string }>({});
  const [passwordStatus, setPasswordStatus] = useState<{ ok?: boolean; msg?: string }>({});
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (!isLoading && !isLoggedIn) router.push('/account/login');
  }, [isLoading, isLoggedIn, router]);

  useEffect(() => {
    if (customer) {
      setProfileForm({
        salutationId: customer.salutationId || '',
        firstName: customer.firstName,
        lastName: customer.lastName,
      });
    }
  }, [customer]);

  useEffect(() => {
    getSalutations()
      .then((d) => setSalutations(d.elements || []))
      .catch(() => {});
  }, []);

  if (isLoading || !customer) {
    return (
      <div className="min-h-[60vh] flex items-center justify-center">
        <svg className="w-6 h-6 animate-spin text-surface-400" viewBox="0 0 24 24" fill="none">
          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
        </svg>
      </div>
    );
  }

  const handleProfileSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setProfileStatus({});
    try {
      await updateProfile(profileForm);
      await refreshCustomer();
      setProfileStatus({ ok: true, msg: 'Profile updated successfully.' });
    } catch (err: any) {
      setProfileStatus({ ok: false, msg: err.message || 'Failed to update profile.' });
    } finally {
      setSubmitting(false);
    }
  };

  const handleEmailSave = async (e: React.FormEvent) => {
    e.preventDefault();
    if (emailForm.email !== emailForm.emailConfirmation) {
      setEmailStatus({ ok: false, msg: 'Email addresses do not match.' });
      return;
    }
    setSubmitting(true);
    setEmailStatus({});
    try {
      await changeEmail(emailForm);
      await refreshCustomer();
      setEmailStatus({ ok: true, msg: 'Email updated successfully.' });
      setEmailForm({ email: '', emailConfirmation: '', password: '' });
    } catch (err: any) {
      setEmailStatus({ ok: false, msg: err.message || 'Failed to update email.' });
    } finally {
      setSubmitting(false);
    }
  };

  const handlePasswordSave = async (e: React.FormEvent) => {
    e.preventDefault();
    if (passwordForm.newPassword !== passwordForm.newPasswordConfirm) {
      setPasswordStatus({ ok: false, msg: 'New passwords do not match.' });
      return;
    }
    if (passwordForm.newPassword.length < 8) {
      setPasswordStatus({ ok: false, msg: 'Password must be at least 8 characters.' });
      return;
    }
    setSubmitting(true);
    setPasswordStatus({});
    try {
      await changePassword(passwordForm);
      setPasswordStatus({ ok: true, msg: 'Password changed successfully.' });
      setPasswordForm({ password: '', newPassword: '', newPasswordConfirm: '' });
    } catch (err: any) {
      setPasswordStatus({ ok: false, msg: err.message || 'Failed to change password.' });
    } finally {
      setSubmitting(false);
    }
  };

  const inputClass =
    'w-full px-4 py-3 rounded-xl border border-surface-200 focus:border-brand-500 focus:ring-2 focus:ring-brand-500/20 outline-none transition-all text-surface-900';

  const tabs: { id: Section; label: string }[] = [
    { id: 'profile', label: 'Personal Info' },
    { id: 'email', label: 'Email Address' },
    { id: 'password', label: 'Password' },
  ];

  return (
    <div className="max-w-5xl mx-auto px-6 py-10">
      <div className="grid md:grid-cols-[220px_1fr] gap-8">
        {/* Sidebar */}
        <AccountNav />

        {/* Main content */}
        <div>
          <h1 className="text-2xl font-bold text-surface-900 mb-6">Profile Settings</h1>

          {/* Tab buttons */}
          <div className="flex gap-1 bg-surface-100 p-1 rounded-xl mb-8 w-fit">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveSection(tab.id)}
                className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
                  activeSection === tab.id
                    ? 'bg-white text-surface-900 shadow-sm'
                    : 'text-surface-500 hover:text-surface-700'
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>

          {/* Personal Info */}
          {activeSection === 'profile' && (
            <div className="bg-white border border-surface-200 rounded-2xl p-6">
              <h2 className="text-lg font-semibold mb-6">Personal Information</h2>
              {profileStatus.msg && (
                <div className={`mb-5 p-4 rounded-xl text-sm ${profileStatus.ok ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'}`}>
                  {profileStatus.msg}
                </div>
              )}
              <form onSubmit={handleProfileSave} className="space-y-5">
                <div>
                  <label className="block text-sm font-medium text-surface-700 mb-1.5">Salutation</label>
                  <select
                    value={profileForm.salutationId}
                    onChange={(e) => setProfileForm((p) => ({ ...p, salutationId: e.target.value }))}
                    className={inputClass}
                  >
                    <option value="">Select...</option>
                    {salutations.map((s) => (
                      <option key={s.id} value={s.id}>{s.translated?.displayName || s.displayName}</option>
                    ))}
                  </select>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-surface-700 mb-1.5">First Name</label>
                    <input
                      type="text"
                      required
                      value={profileForm.firstName}
                      onChange={(e) => setProfileForm((p) => ({ ...p, firstName: e.target.value }))}
                      className={inputClass}
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-surface-700 mb-1.5">Last Name</label>
                    <input
                      type="text"
                      required
                      value={profileForm.lastName}
                      onChange={(e) => setProfileForm((p) => ({ ...p, lastName: e.target.value }))}
                      className={inputClass}
                    />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-surface-700 mb-1.5">Email (read-only)</label>
                  <input type="email" value={customer.email} disabled className={`${inputClass} bg-surface-50 text-surface-400 cursor-not-allowed`} />
                  <p className="text-xs text-surface-400 mt-1">To change your email, use the &ldquo;Email Address&rdquo; tab.</p>
                </div>
                <button
                  type="submit"
                  disabled={submitting}
                  className="px-6 py-3 bg-brand-500 hover:bg-brand-600 disabled:bg-brand-300 text-white font-semibold rounded-xl transition-colors"
                >
                  {submitting ? 'Saving...' : 'Save Changes'}
                </button>
              </form>
            </div>
          )}

          {/* Email Change */}
          {activeSection === 'email' && (
            <div className="bg-white border border-surface-200 rounded-2xl p-6">
              <h2 className="text-lg font-semibold mb-2">Change Email Address</h2>
              <p className="text-sm text-surface-500 mb-6">Current email: <strong>{customer.email}</strong></p>
              {emailStatus.msg && (
                <div className={`mb-5 p-4 rounded-xl text-sm ${emailStatus.ok ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'}`}>
                  {emailStatus.msg}
                </div>
              )}
              <form onSubmit={handleEmailSave} className="space-y-5">
                <div>
                  <label className="block text-sm font-medium text-surface-700 mb-1.5">New Email</label>
                  <input type="email" required value={emailForm.email} onChange={(e) => setEmailForm((p) => ({ ...p, email: e.target.value }))} className={inputClass} placeholder="new@email.com" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-surface-700 mb-1.5">Confirm New Email</label>
                  <input type="email" required value={emailForm.emailConfirmation} onChange={(e) => setEmailForm((p) => ({ ...p, emailConfirmation: e.target.value }))} className={inputClass} placeholder="new@email.com" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-surface-700 mb-1.5">Current Password</label>
                  <input type="password" required value={emailForm.password} onChange={(e) => setEmailForm((p) => ({ ...p, password: e.target.value }))} className={inputClass} placeholder="••••••••" />
                </div>
                <button type="submit" disabled={submitting} className="px-6 py-3 bg-brand-500 hover:bg-brand-600 disabled:bg-brand-300 text-white font-semibold rounded-xl transition-colors">
                  {submitting ? 'Saving...' : 'Update Email'}
                </button>
              </form>
            </div>
          )}

          {/* Password Change */}
          {activeSection === 'password' && (
            <div className="bg-white border border-surface-200 rounded-2xl p-6">
              <h2 className="text-lg font-semibold mb-6">Change Password</h2>
              {passwordStatus.msg && (
                <div className={`mb-5 p-4 rounded-xl text-sm ${passwordStatus.ok ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'}`}>
                  {passwordStatus.msg}
                </div>
              )}
              <form onSubmit={handlePasswordSave} className="space-y-5">
                <div>
                  <label className="block text-sm font-medium text-surface-700 mb-1.5">Current Password</label>
                  <input type="password" required value={passwordForm.password} onChange={(e) => setPasswordForm((p) => ({ ...p, password: e.target.value }))} className={inputClass} placeholder="••••••••" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-surface-700 mb-1.5">New Password</label>
                  <input type="password" required minLength={8} value={passwordForm.newPassword} onChange={(e) => setPasswordForm((p) => ({ ...p, newPassword: e.target.value }))} className={inputClass} placeholder="Min. 8 characters" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-surface-700 mb-1.5">Confirm New Password</label>
                  <input type="password" required value={passwordForm.newPasswordConfirm} onChange={(e) => setPasswordForm((p) => ({ ...p, newPasswordConfirm: e.target.value }))} className={inputClass} placeholder="Repeat new password" />
                </div>
                <button type="submit" disabled={submitting} className="px-6 py-3 bg-brand-500 hover:bg-brand-600 disabled:bg-brand-300 text-white font-semibold rounded-xl transition-colors">
                  {submitting ? 'Changing...' : 'Change Password'}
                </button>
              </form>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
