'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { api, apiPaths } from '@/lib/api';
import { getUser, setUser } from '@/lib/auth';
import { useAuthGuard } from '@/lib/useAuthGuard';
import { useI18n } from '@/lib/i18n/context';
import type { Locale } from '@/lib/i18n/types';
import ContactModal from '@/app/components/ContactModal';

export default function SettingsPage() {
  const router = useRouter();
  const { t, locale, setLocale, isRtl } = useI18n();
  const { checked } = useAuthGuard('/login', { requireApproval: false });
  const sessionUser = getUser();
  const [showContactModal, setShowContactModal] = useState(false);
  const [showPasswordModal, setShowPasswordModal] = useState(false);
  const [showPhoneModal, setShowPhoneModal] = useState(false);
  const [showLanguageModal, setShowLanguageModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deletePassword, setDeletePassword] = useState('');
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [deleteError, setDeleteError] = useState('');
  const [notificationsEnabled, setNotificationsEnabled] = useState(true);
  const [notificationSaving, setNotificationSaving] = useState(false);
  const [notificationError, setNotificationError] = useState('');
  const [showSuccess, setShowSuccess] = useState(false);
  const [pwdLoading, setPwdLoading] = useState(false);
  const [pwdError, setPwdError] = useState('');
  const [langSaving, setLangSaving] = useState(false);
  const [langError, setLangError] = useState('');

  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [newPasswordConfirmation, setNewPasswordConfirmation] = useState('');

  const [currentOtp, setCurrentOtp] = useState('');
  const [newPhone, setNewPhone] = useState('');
  const [newOtp, setNewOtp] = useState('');

  const [selectedLanguage, setSelectedLanguage] = useState<Locale>('ar');

  useEffect(() => {
    if (showLanguageModal) {
      setSelectedLanguage(locale);
      setLangError('');
    }
  }, [showLanguageModal, locale]);

  useEffect(() => {
    const u = getUser();
    if (typeof u?.is_notify === 'boolean') {
      setNotificationsEnabled(u.is_notify);
    }
  }, []);

  const handleChangePhone = () => {
    if (!currentOtp || !newPhone || !newOtp) {
      alert(t('settings.fillAllFields'));
      return;
    }
    setShowPhoneModal(false);
    setShowSuccess(true);
    setTimeout(() => setShowSuccess(false), 3000);
  };

  const handleNotificationToggle = async () => {
    const u = getUser();
    if (u?.is_approved === false) {
      setNotificationError(t('settings.notificationsNeedApproval'));
      return;
    }
    setNotificationError('');
    setNotificationSaving(true);
    try {
      const res = await api.patch<{ is_notify?: number }>(apiPaths.user.notificationSwitch, {});
      if (res.key === 'success' && res.data && typeof res.data.is_notify !== 'undefined') {
        const on = Boolean(res.data.is_notify);
        setNotificationsEnabled(on);
        if (u) setUser({ ...u, is_notify: on });
      } else {
        setNotificationError(res.msg || t('settings.notificationToggleError'));
      }
    } catch {
      setNotificationError(t('settings.serverError'));
    } finally {
      setNotificationSaving(false);
    }
  };

  const handleChangeLanguage = async () => {
    setLangSaving(true);
    setLangError('');
    const ok = await setLocale(selectedLanguage);
    setLangSaving(false);
    if (ok) {
      setShowLanguageModal(false);
      setShowSuccess(true);
      setTimeout(() => setShowSuccess(false), 3000);
    } else {
      setLangError(t('settings.langChangeError'));
    }
  };

  const handleDeleteAccount = async () => {
    setDeleteError('');
    if (!deletePassword) {
      setDeleteError(t('settings.fillAllFields'));
      return;
    }
    setDeleteLoading(true);
    try {
      const res = await api.deleteWithBody(apiPaths.user.deleteAccount, { password: deletePassword });
      if (res.key === 'success') {
        setShowDeleteModal(false);
        const { logout } = await import('@/lib/auth');
        await logout();
        router.push('/login');
        return;
      }
      setDeleteError(res.msg || t('settings.deleteError'));
    } catch {
      setDeleteError(t('settings.serverError'));
    } finally {
      setDeleteLoading(false);
    }
  };

  const handleChangePassword = async () => {
    setPwdError('');
    if (!currentPassword || !newPassword || newPassword.length < 6) {
      setPwdError(t('settings.pwdRules'));
      return;
    }
    if (newPassword !== newPasswordConfirmation) {
      setPwdError(t('settings.pwdMismatch'));
      return;
    }
    setPwdLoading(true);
    try {
      const res = await api.post(apiPaths.user.changePassword, {
        current_password: currentPassword,
        new_password: newPassword,
        new_password_confirmation: newPasswordConfirmation,
      });
      if (res.key === 'success') {
        setShowPasswordModal(false);
        setCurrentPassword('');
        setNewPassword('');
        setNewPasswordConfirmation('');
        setShowSuccess(true);
        setTimeout(() => setShowSuccess(false), 3000);
      } else {
        setPwdError(res.msg || t('settings.pwdChangeFail'));
      }
    } catch {
      setPwdError(t('settings.serverError'));
    } finally {
      setPwdLoading(false);
    }
  };

  const backIcon = isRtl ? 'ri-arrow-right-line' : 'ri-arrow-left-line';
  const chevronIcon = isRtl ? 'ri-arrow-left-s-line' : 'ri-arrow-right-s-line';

  /** صف إعداد واحد — مطابق لنمط البطاقات في التصميم المرجعي */
  const settingsRowClass =
    'w-full rounded-2xl border border-gray-100 bg-white px-5 py-4 sm:px-6 sm:py-5 shadow-[0_1px_3px_rgba(15,23,42,0.07)] flex items-center justify-between gap-4 transition-all hover:shadow-md hover:border-gray-200/90';

  if (!checked) return null;

  return (
    <div dir={isRtl ? 'rtl' : 'ltr'} className="flex flex-col flex-1 bg-[#f3f4f6]">
      {showSuccess && (
        <div className="fixed top-20 left-1/2 transform -translate-x-1/2 bg-green-50 border border-green-200 text-green-800 px-6 py-3 rounded-lg shadow-lg z-50 flex items-center gap-2">
          <i className="ri-check-line text-xl"></i>
          <span className="font-semibold whitespace-nowrap">{t('common.successSaved')}</span>
        </div>
      )}

      {showPasswordModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl p-6 max-w-md w-full">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-xl font-bold text-gray-900">{t('settings.passwordModalTitle')}</h3>
              <button
                type="button"
                onClick={() => { setShowPasswordModal(false); setPwdError(''); }}
                className="w-8 h-8 flex items-center justify-center text-gray-500 hover:bg-gray-100 rounded-lg transition-colors cursor-pointer"
              >
                <i className="ri-close-line text-xl"></i>
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">{t('settings.currentPassword')}</label>
                <input
                  type="password"
                  value={currentPassword}
                  onChange={(e) => setCurrentPassword(e.target.value)}
                  className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  autoComplete="current-password"
                />
              </div>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">{t('settings.newPassword')}</label>
                <input
                  type="password"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  autoComplete="new-password"
                  minLength={6}
                />
              </div>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">{t('settings.confirmPassword')}</label>
                <input
                  type="password"
                  value={newPasswordConfirmation}
                  onChange={(e) => setNewPasswordConfirmation(e.target.value)}
                  className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  autoComplete="new-password"
                  minLength={6}
                />
              </div>
              {pwdError && <p className="text-red-600 text-sm">{pwdError}</p>}
              <button
                type="button"
                onClick={handleChangePassword}
                disabled={pwdLoading}
                className="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 disabled:opacity-60 font-semibold cursor-pointer"
              >
                {pwdLoading ? t('settings.saving') : t('settings.savePassword')}
              </button>
            </div>
          </div>
        </div>
      )}

      {showPhoneModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl p-6 max-w-md w-full">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-xl font-bold text-gray-900">{t('settings.phoneModalTitle')}</h3>
              <button
                type="button"
                onClick={() => setShowPhoneModal(false)}
                className="w-8 h-8 flex items-center justify-center text-gray-500 hover:bg-gray-100 rounded-lg transition-colors cursor-pointer"
              >
                <i className="ri-close-line text-xl"></i>
              </button>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  {t('settings.currentOtp')}
                </label>
                <input
                  type="text"
                  value={currentOtp}
                  onChange={(e) => setCurrentOtp(e.target.value)}
                  placeholder={t('settings.enterCode')}
                  className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  {t('settings.newPhone')}
                </label>
                <input
                  type="tel"
                  value={newPhone}
                  onChange={(e) => setNewPhone(e.target.value)}
                  placeholder="+966 50 123 4567"
                  dir="ltr"
                  className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  {t('settings.newOtp')}
                </label>
                <input
                  type="text"
                  value={newOtp}
                  onChange={(e) => setNewOtp(e.target.value)}
                  placeholder={t('settings.enterCode')}
                  className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <button
                type="button"
                onClick={handleChangePhone}
                className="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 transition-colors cursor-pointer whitespace-nowrap font-semibold"
              >
                {t('settings.confirmChange')}
              </button>
            </div>
          </div>
        </div>
      )}

      {showLanguageModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl p-6 max-w-md w-full">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-xl font-bold text-gray-900">{t('settings.languageModalTitle')}</h3>
              <button
                type="button"
                onClick={() => setShowLanguageModal(false)}
                className="w-8 h-8 flex items-center justify-center text-gray-500 hover:bg-gray-100 rounded-lg transition-colors cursor-pointer"
              >
                <i className="ri-close-line text-xl"></i>
              </button>
            </div>

            <div className="space-y-3">
              <button
                type="button"
                onClick={() => setSelectedLanguage('ar')}
                className={`w-full p-4 rounded-lg border-2 transition-colors cursor-pointer flex items-center justify-between ${
                  selectedLanguage === 'ar'
                    ? 'border-blue-600 bg-blue-50'
                    : 'border-gray-200 hover:border-blue-300'
                }`}
              >
                <span className="font-semibold text-gray-900">{t('settings.arabic')}</span>
                {selectedLanguage === 'ar' && (
                  <i className="ri-check-line text-xl text-blue-600"></i>
                )}
              </button>

              <button
                type="button"
                onClick={() => setSelectedLanguage('en')}
                className={`w-full p-4 rounded-lg border-2 transition-colors cursor-pointer flex items-center justify-between ${
                  selectedLanguage === 'en'
                    ? 'border-blue-600 bg-blue-50'
                    : 'border-gray-200 hover:border-blue-300'
                }`}
              >
                <span className="font-semibold text-gray-900">{t('settings.english')}</span>
                {selectedLanguage === 'en' && (
                  <i className="ri-check-line text-xl text-blue-600"></i>
                )}
              </button>

              {langError && <p className="text-red-600 text-sm">{langError}</p>}

              <button
                type="button"
                onClick={() => void handleChangeLanguage()}
                disabled={langSaving}
                className="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 transition-colors cursor-pointer whitespace-nowrap font-semibold mt-4 disabled:opacity-60"
              >
                {langSaving ? t('settings.saving') : t('common.save')}
              </button>
            </div>
          </div>
        </div>
      )}

      {showDeleteModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl p-6 max-w-md w-full">
            <div className="flex items-center justify-center mb-4">
              <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center">
                <i className="ri-error-warning-line text-3xl text-red-600"></i>
              </div>
            </div>
            <h3 className="text-xl font-bold text-gray-900 text-center mb-2">{t('settings.deleteTitle')}</h3>
            <p className="text-gray-600 text-center mb-4">
              {t('settings.deleteBody')}
            </p>
            <div className="mb-4">
              <label className="block text-sm font-semibold text-gray-700 mb-2">{t('settings.deletePassword')}</label>
              <input
                type="password"
                value={deletePassword}
                onChange={(e) => setDeletePassword(e.target.value)}
                className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
                autoComplete="current-password"
              />
            </div>
            {deleteError && <p className="text-red-600 text-sm text-center mb-3">{deleteError}</p>}

            <div className="flex gap-3">
              <button
                type="button"
                onClick={() => { setShowDeleteModal(false); setDeletePassword(''); setDeleteError(''); }}
                className="flex-1 bg-gray-100 text-gray-700 py-3 rounded-lg hover:bg-gray-200 transition-colors cursor-pointer whitespace-nowrap font-semibold"
              >
                {t('common.cancel')}
              </button>
              <button
                type="button"
                onClick={() => void handleDeleteAccount()}
                disabled={deleteLoading}
                className="flex-1 bg-red-600 text-white py-3 rounded-lg hover:bg-red-700 transition-colors cursor-pointer whitespace-nowrap font-semibold disabled:opacity-60"
              >
                {deleteLoading ? t('settings.saving') : t('settings.deleteAccount')}
              </button>
            </div>
          </div>
        </div>
      )}

      <main className="w-full max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-10 sm:py-12">
        <div className="flex items-center gap-3 sm:gap-4 mb-8 sm:mb-10">
          <Link
            href="/profile"
            className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-gray-200 bg-white text-gray-700 shadow-sm transition-colors hover:bg-gray-50 cursor-pointer"
          >
            <i className={`${backIcon} text-xl`} aria-hidden />
          </Link>
          <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-gray-900">{t('settings.title')}</h1>
        </div>

        <div className="flex flex-col gap-4">
          <button
            type="button"
            onClick={() => setShowPasswordModal(true)}
            className={`${settingsRowClass} cursor-pointer text-start`}
          >
            <span className="flex min-w-0 flex-1 items-center gap-4">
              <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-indigo-100">
                <i className="ri-lock-password-line text-2xl text-indigo-600" aria-hidden />
              </span>
              <span className="text-base font-semibold text-gray-900 sm:text-lg">{t('settings.changePassword')}</span>
            </span>
            <i className={`${chevronIcon} shrink-0 text-xl text-gray-400`} aria-hidden />
          </button>

          <button
            type="button"
            onClick={() => setShowPhoneModal(true)}
            className={`${settingsRowClass} cursor-pointer text-start`}
          >
            <span className="flex min-w-0 flex-1 items-center gap-4">
              <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-sky-100">
                <i className="ri-smartphone-line text-2xl text-sky-600" aria-hidden />
              </span>
              <span className="text-base font-semibold text-gray-900 sm:text-lg">{t('settings.changePhone')}</span>
            </span>
            <i className={`${chevronIcon} shrink-0 text-xl text-gray-400`} aria-hidden />
          </button>

          <button
            type="button"
            onClick={() => setShowLanguageModal(true)}
            className={`${settingsRowClass} cursor-pointer text-start`}
          >
            <span className="flex min-w-0 flex-1 items-center gap-4">
              <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-violet-100">
                <i className="ri-global-line text-2xl text-violet-600" aria-hidden />
              </span>
              <span className="text-base font-semibold text-gray-900 sm:text-lg">{t('settings.changeLanguage')}</span>
            </span>
            <i className={`${chevronIcon} shrink-0 text-xl text-gray-400`} aria-hidden />
          </button>

          <div className={settingsRowClass}>
            <span className="flex min-w-0 flex-1 items-center gap-4">
              <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-emerald-100">
                <i className="ri-notification-3-line text-2xl text-emerald-600" aria-hidden />
              </span>
              <span className="text-base font-semibold text-gray-900 sm:text-lg">{t('settings.notifications')}</span>
            </span>
            <span className="flex shrink-0 flex-col items-end gap-1">
              <button
                type="button"
                onClick={() => void handleNotificationToggle()}
                disabled={notificationSaving || sessionUser?.is_approved === false}
                className={`relative h-8 w-14 shrink-0 rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-[#1e3a5f]/30 focus:ring-offset-2 ${
                  notificationsEnabled ? 'bg-[#1e3a5f]' : 'bg-gray-300'
                } ${notificationSaving || sessionUser?.is_approved === false ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'}`}
                aria-pressed={notificationsEnabled}
              >
                <span
                  className={`absolute top-1 h-6 w-6 rounded-full bg-white shadow-md transition-all ${
                    notificationsEnabled ? 'end-1' : 'start-1'
                  }`}
                />
              </button>
              {notificationError && (
                <span className="max-w-[14rem] text-end text-xs text-red-600">{notificationError}</span>
              )}
            </span>
          </div>

          <button
            type="button"
            onClick={() => setShowContactModal(true)}
            className={`${settingsRowClass} cursor-pointer text-start`}
          >
            <span className="flex min-w-0 flex-1 items-center gap-4">
              <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-orange-100">
                <i className="ri-customer-service-2-line text-2xl text-orange-600" aria-hidden />
              </span>
              <span className="text-base font-semibold text-gray-900 sm:text-lg">{t('settings.contactUs')}</span>
            </span>
            <i className={`${chevronIcon} shrink-0 text-xl text-gray-400`} aria-hidden />
          </button>

          <button
            type="button"
            onClick={() => setShowDeleteModal(true)}
            className={`${settingsRowClass} cursor-pointer border-red-100 text-start hover:border-red-200/80`}
          >
            <span className="flex min-w-0 flex-1 items-center gap-4">
              <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-red-100">
                <i className="ri-delete-bin-line text-2xl text-red-600" aria-hidden />
              </span>
              <span className="text-base font-semibold text-red-600 sm:text-lg">{t('settings.deleteAccount')}</span>
            </span>
            <i className={`${chevronIcon} shrink-0 text-xl text-gray-400`} aria-hidden />
          </button>

          <Link href="/profile/about" className={`${settingsRowClass} cursor-pointer`}>
            <span className="flex min-w-0 flex-1 items-center gap-4">
              <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-slate-100">
                <i className="ri-settings-3-line text-2xl text-slate-600" aria-hidden />
              </span>
              <span className="text-base font-semibold text-gray-900 sm:text-lg">{t('settings.about')}</span>
            </span>
            <i className={`${chevronIcon} shrink-0 text-xl text-gray-400`} aria-hidden />
          </Link>

          <Link href="/profile/terms" className={`${settingsRowClass} cursor-pointer`}>
            <span className="flex min-w-0 flex-1 items-center gap-4">
              <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-amber-100">
                <i className="ri-file-text-line text-2xl text-amber-600" aria-hidden />
              </span>
              <span className="text-base font-semibold text-gray-900 sm:text-lg">{t('settings.terms')}</span>
            </span>
            <i className={`${chevronIcon} shrink-0 text-xl text-gray-400`} aria-hidden />
          </Link>

          <Link href="/profile/privacy" className={`${settingsRowClass} cursor-pointer`}>
            <span className="flex min-w-0 flex-1 items-center gap-4">
              <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-rose-100">
                <i className="ri-shield-check-line text-2xl text-rose-700" aria-hidden />
              </span>
              <span className="text-base font-semibold text-gray-900 sm:text-lg">{t('settings.privacy')}</span>
            </span>
            <i className={`${chevronIcon} shrink-0 text-xl text-gray-400`} aria-hidden />
          </Link>
        </div>
      </main>

      <ContactModal open={showContactModal} onClose={() => setShowContactModal(false)} />
    </div>
  );
}
