'use client';

import { useState, useEffect, useRef } from 'react';
import { AppToast } from '@/app/components/AppToast';
import type { Toast } from 'primereact/toast';
import DashboardShell from '../components/DashboardShell';
import { useApi } from '@/hooks/useApi';

interface ProfileData {
  id: number;
  image: string;
  name: string;
  phone: string;
  country_code: string;
  email: string;
  city_id?: number | null;
  city_name: string;
  commercial_register_number: string;
  description: string;
  bank_name: string | null;
  account_holder_name: string | null;
  account_number: string | null;
  iban: string | null;
}

interface ProfileResponse {
  key: string;
  msg: string;
  data: ProfileData;
}

interface ApiActionResponse {
  key?: string;
  msg?: string;
  message?: string;
}

function isSuccessKey(key: unknown): boolean {
  return String(key ?? '').toLowerCase() === 'success';
}

export default function DashboardSettingsPage() {
  const toastRef = useRef<Toast>(null);
  const [activeTab, setActiveTab] = useState('company');
  const [saved, setSaved] = useState(false);

  const { request: fetchProfile, loading: profileLoading } = useApi<ProfileResponse>();
  const { request: updateProfile, loading: updateLoading, lastError: updateLastError } = useApi<ProfileResponse>();
  const { request: changePassword, loading: passwordLoading, lastError: passwordLastError } = useApi<ApiActionResponse>();

  const [profile, setProfile] = useState<ProfileData | null>(null);

  // Form state
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    city_id: '',
    commercial_register_number: '',
    city_name: '',
    description: '',
    bank_name: '',
    account_holder_name: '',
    account_number: '',
    iban: '',
  });

  const [passwordForm, setPasswordForm] = useState({
    old_password: '',
    password: '',
    password_confirmation: '',
  });

  const [passwordError, setPasswordError] = useState<string | null>(null);
  const [passwordSuccess, setPasswordSuccess] = useState(false);

  const logoInputRef = useRef<HTMLInputElement>(null);
  /** ملف شعار جديد يُرسل مع الحفظ */
  const [pendingLogoFile, setPendingLogoFile] = useState<File | null>(null);
  /** معاينة محلية قبل الحفظ */
  const [logoPreviewUrl, setLogoPreviewUrl] = useState<string | null>(null);

  useEffect(() => {
    return () => {
      if (logoPreviewUrl) URL.revokeObjectURL(logoPreviewUrl);
    };
  }, [logoPreviewUrl]);

  useEffect(() => {
    fetchProfile('account/profile').then((res) => {
      if (res?.data) {
        setProfile(res.data);
        setFormData({
          name: res.data.name ?? '',
          email: res.data.email ?? '',
          phone: res.data.phone ?? '',
          city_id: res.data.city_id != null ? String(res.data.city_id) : '',
          commercial_register_number: res.data.commercial_register_number ?? '',
          city_name: res.data.city_name ?? '',
          description: res.data.description ?? '',
          bank_name: res.data.bank_name ?? '',
          account_holder_name: res.data.account_holder_name ?? '',
          account_number: res.data.account_number ?? '',
          iban: res.data.iban ?? '',
        });
      }
    });
  }, []);

  function handleLogoFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!file.type.startsWith('image/')) {
      toastRef.current?.show({
        severity: 'warn',
        summary: 'نوع الملف',
        detail: 'يرجى اختيار صورة (PNG أو JPG)',
        life: 3500,
      });
      e.target.value = '';
      return;
    }

    const maxBytes = 2 * 1024 * 1024;
    if (file.size > maxBytes) {
      toastRef.current?.show({
        severity: 'warn',
        summary: 'حجم كبير',
        detail: 'الحد الأقصى لحجم الشعار 2 ميجابايت',
        life: 3500,
      });
      e.target.value = '';
      return;
    }

    setPendingLogoFile(file);
    setLogoPreviewUrl((prev) => {
      if (prev) URL.revokeObjectURL(prev);
      return URL.createObjectURL(file);
    });
  }

  function clearPendingLogo() {
    setPendingLogoFile(null);
    setLogoPreviewUrl((prev) => {
      if (prev) URL.revokeObjectURL(prev);
      return null;
    });
    if (logoInputRef.current) logoInputRef.current.value = '';
  }

  async function handleSave() {
    const body = new FormData();
    body.append('name', formData.name);
    body.append('email', formData.email);
    body.append('phone', formData.phone);
    if (formData.city_id) body.append('city_id', formData.city_id);
    body.append('commercial_register_number', formData.commercial_register_number);
    body.append('description', formData.description);
    if (formData.bank_name) body.append('bank_name', formData.bank_name);
    if (formData.account_holder_name) body.append('account_holder_name', formData.account_holder_name);
    if (formData.account_number) body.append('account_number', formData.account_number);
    if (formData.iban) body.append('iban', formData.iban);
    if (pendingLogoFile) {
      body.append('image', pendingLogoFile);
    }

    const res = await updateProfile('account/profile/update', { method: 'POST', body });
    if (!res) {
      toastRef.current?.show({
        severity: 'error',
        summary: 'فشل التحديث',
        detail: updateLastError.current || 'تعذر تحديث بيانات الشركة',
        life: 3500,
      });
      return;
    }

    if (isSuccessKey(res.key) && res.data) {
      setProfile(res.data);
      clearPendingLogo();
      setSaved(true);
      setTimeout(() => setSaved(false), 2500);
      toastRef.current?.show({
        severity: 'success',
        summary: 'تم بنجاح',
        detail: res.msg || 'تم تحديث بيانات الشركة بنجاح',
        life: 3000,
      });
      return;
    }

    toastRef.current?.show({
      severity: 'error',
      summary: 'فشل التحديث',
      detail: res.msg || 'تعذر تحديث بيانات الشركة',
      life: 3500,
    });
  }

  async function handleChangePassword() {
    setPasswordError(null);
    if (passwordForm.password !== passwordForm.password_confirmation) {
      setPasswordError('كلمة المرور الجديدة وتأكيدها غير متطابقين');
      toastRef.current?.show({
        severity: 'error',
        summary: 'فشل التحديث',
        detail: 'كلمة المرور الجديدة وتأكيدها غير متطابقين',
        life: 3500,
      });
      return;
    }
    const res = await changePassword('account/profile/change-password', {
      method: 'POST',
      body: passwordForm,
    });
    if (!res) {
      toastRef.current?.show({
        severity: 'error',
        summary: 'فشل التحديث',
        detail: passwordLastError.current || 'تعذر تغيير كلمة المرور',
        life: 3500,
      });
      return;
    }

    if (isSuccessKey(res.key)) {
      setPasswordSuccess(true);
      setPasswordForm({ old_password: '', password: '', password_confirmation: '' });
      setTimeout(() => setPasswordSuccess(false), 2500);
      toastRef.current?.show({
        severity: 'success',
        summary: 'تم بنجاح',
        detail: res.msg || res.message || 'تم تغيير كلمة المرور بنجاح',
        life: 3000,
      });
      return;
    }

    toastRef.current?.show({
      severity: 'error',
      summary: 'فشل التحديث',
      detail: res.msg || res.message || 'تعذر تغيير كلمة المرور',
      life: 3500,
    });
  }

  const tabs = [
    { id: 'company', label: 'بيانات الشركة', icon: 'ri-building-2-line' },
    { id: 'security', label: 'الأمان', icon: 'ri-shield-keyhole-line' },
  ];

  return (
    <DashboardShell title="الإعدادات" subtitle="إدارة إعدادات الشركة والنظام">
      <AppToast ref={toastRef} />
      <div className="flex gap-6">
        {/* Sidebar Tabs */}
        <div className="w-56 flex-shrink-0">
          <div className="bg-white rounded-2xl p-2" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
            {tabs.map(t => (
              <button
                key={t.id}
                onClick={() => setActiveTab(t.id)}
                className="w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-bold cursor-pointer transition-all mb-1 whitespace-nowrap"
                style={{
                  background: activeTab === t.id ? '#EEF2FF' : 'transparent',
                  color: activeTab === t.id ? '#1E3A8A' : '#64748b',
                  fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                }}
              >
                <div className="w-5 h-5 flex items-center justify-center flex-shrink-0">
                  <i className={`${t.icon} text-base`}></i>
                </div>
                {t.label}
              </button>
            ))}
          </div>
        </div>

        {/* Content */}
        <div className="flex-1">

          {/* Company Info */}
          {activeTab === 'company' && (
            <div className="bg-white rounded-2xl p-7" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
              <h2 className="text-base font-black text-slate-900 mb-6" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>بيانات الشركة</h2>

              {profileLoading ? (
                <div className="flex items-center justify-center py-16">
                  <div className="w-8 h-8 rounded-full border-2 border-blue-200 border-t-blue-700 animate-spin"></div>
                </div>
              ) : (
                <>
                  {/* Logo */}
                  <div className="flex items-center gap-5 mb-7 p-5 rounded-2xl" style={{ background: '#F8FAFC' }}>
                    <input
                      ref={logoInputRef}
                      type="file"
                      accept="image/png,image/jpeg,image/jpg,image/webp"
                      className="hidden"
                      onChange={handleLogoFileChange}
                    />
                    <div className="relative flex-shrink-0">
                      <button
                        type="button"
                        onClick={() => logoInputRef.current?.click()}
                        className="w-20 h-20 rounded-2xl flex items-center justify-center overflow-hidden ring-offset-2 ring-offset-[#F8FAFC] transition-all hover:ring-2 hover:ring-blue-400 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
                        style={{ background: '#1E3A8A' }}
                        aria-label="تغيير شعار الشركة"
                      >
                        {logoPreviewUrl || profile?.image ? (
                          <img
                            src={logoPreviewUrl ?? profile?.image ?? ''}
                            alt="شعار الشركة"
                            className="w-full h-full object-cover"
                          />
                        ) : (
                          <i className="ri-bus-2-fill text-white text-4xl"></i>
                        )}
                      </button>
                      {/* <button
                        type="button"
                        onClick={() => logoInputRef.current?.click()}
                        className="absolute -bottom-1 -left-1 w-8 h-8 rounded-xl bg-white border border-slate-200 shadow-md flex items-center justify-center cursor-pointer hover:bg-slate-50 transition-colors"
                        aria-label="رفع صورة"
                      >
                        <i className="ri-camera-line text-slate-700 text-lg"></i>
                      </button> */}
                    </div>
                    <div>
                      <p className="font-bold text-slate-800 text-sm mb-1" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>شعار الشركة</p>
                      <p className="text-xs text-slate-400 mb-3" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>PNG أو JPG بحجم أقصى 2MB</p>
                      <div className="flex flex-wrap items-center gap-2">
                        <button
                          type="button"
                          onClick={() => logoInputRef.current?.click()}
                          className="px-4 py-2 rounded-xl text-xs font-bold cursor-pointer whitespace-nowrap"
                          style={{ background: '#EEF2FF', color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                        >
                          <i className="ri-upload-2-line ml-1"></i>
                          رفع شعار جديد
                        </button>
                        {pendingLogoFile && (
                          <button
                            type="button"
                            onClick={clearPendingLogo}
                            className="px-3 py-2 rounded-xl text-xs font-bold text-slate-600 bg-slate-100 hover:bg-slate-200 whitespace-nowrap"
                            style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                          >
                            إلغاء الصورة المختارة
                          </button>
                        )}
                      </div>
                      {pendingLogoFile && (
                        <p className="text-xs text-amber-700 mt-2 font-semibold" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                          معاينة الشعار الجديد — اضغط «حفظ التغييرات» لرفعه على الخادم
                        </p>
                      )}
                    </div>
                  </div>

                  {/* Fields */}
                  <div className="grid grid-cols-2 gap-5">
                    {[
                      { label: 'اسم الشركة', key: 'name', type: 'text' },
                      { label: 'رقم السجل التجاري', key: 'commercial_register_number', type: 'text' },
                      { label: 'البريد الإلكتروني', key: 'email', type: 'email' },
                      { label: 'رقم الجوال', key: 'phone', type: 'tel' },
                      { label: 'المدينة', key: 'city_name', type: 'text' },
                    ].map((f) => (
                      <div key={f.key}>
                        <label className="block text-sm font-semibold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{f.label}</label>
                        <input
                          type={f.type}
                          value={formData[f.key as keyof typeof formData]}
                          onChange={e => setFormData(prev => ({ ...prev, [f.key]: e.target.value }))}
                          disabled={f.key === 'city_name'}
                          className="w-full h-11 bg-slate-50 border border-slate-200 rounded-xl px-4 text-sm outline-none text-slate-700 transition-all disabled:opacity-60 disabled:cursor-not-allowed"
                          style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                          onFocus={e => (e.target.style.boxShadow = '0 0 0 3px #C7D2FE')}
                          onBlur={e => (e.target.style.boxShadow = 'none')}
                        />
                      </div>
                    ))}
                    <div className="col-span-2">
                      <label className="block text-sm font-semibold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>نبذة عن الشركة</label>
                      <textarea
                        value={formData.description}
                        onChange={e => setFormData(prev => ({ ...prev, description: e.target.value }))}
                        rows={3}
                        className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 text-sm outline-none text-slate-700 resize-none"
                        style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                        onFocus={e => (e.target.style.boxShadow = '0 0 0 3px #C7D2FE')}
                        onBlur={e => (e.target.style.boxShadow = 'none')}
                      />
                    </div>
                  </div>

                  <div className="flex justify-end mt-6">
                    <button
                      onClick={handleSave}
                      disabled={updateLoading}
                      className="flex items-center gap-2 px-6 py-2.5 rounded-xl font-bold text-sm cursor-pointer whitespace-nowrap transition-all disabled:opacity-70"
                      style={{ background: saved ? '#059669' : '#1E3A8A', color: 'white', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                    >
                      {updateLoading
                        ? <><div className="w-4 h-4 rounded-full border-2 border-white/30 border-t-white animate-spin"></div> جاري الحفظ...</>
                        : saved
                          ? <><i className="ri-checkbox-circle-fill text-base"></i> تم الحفظ!</>
                          : <><i className="ri-save-line text-base"></i> حفظ التغييرات</>
                      }
                    </button>
                  </div>
                </>
              )}
            </div>
          )}

          {/* Security */}
          {activeTab === 'security' && (
            <div className="space-y-5">
              <div className="bg-white rounded-2xl p-7" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
                <h2 className="text-base font-black text-slate-900 mb-5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>تغيير كلمة المرور</h2>

                {passwordError && (
                  <div className="mb-4 px-4 py-3 rounded-xl text-sm font-semibold" style={{ background: '#FEE2E2', color: '#DC2626', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                    <i className="ri-error-warning-line ml-1"></i>{passwordError}
                  </div>
                )}
                {passwordSuccess && (
                  <div className="mb-4 px-4 py-3 rounded-xl text-sm font-semibold" style={{ background: '#DCFCE7', color: '#16A34A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                    <i className="ri-checkbox-circle-line ml-1"></i>تم تغيير كلمة المرور بنجاح
                  </div>
                )}

                <div className="space-y-4 max-w-md">
                  {[
                    { label: 'كلمة المرور الحالية', key: 'old_password' },
                    { label: 'كلمة المرور الجديدة', key: 'password' },
                    { label: 'تأكيد كلمة المرور الجديدة', key: 'password_confirmation' },
                  ].map((f) => (
                    <div key={f.key}>
                      <label className="block text-sm font-semibold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{f.label}</label>
                      <input
                        type="password"
                        placeholder="••••••••"
                        value={passwordForm[f.key as keyof typeof passwordForm]}
                        onChange={e => setPasswordForm(prev => ({ ...prev, [f.key]: e.target.value }))}
                        className="w-full h-11 bg-slate-50 border border-slate-200 rounded-xl px-4 text-sm outline-none text-slate-700"
                        style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                      />
                    </div>
                  ))}
                  <button
                    onClick={handleChangePassword}
                    disabled={passwordLoading}
                    className="flex items-center gap-2 px-6 py-2.5 rounded-xl font-bold text-sm cursor-pointer whitespace-nowrap disabled:opacity-70"
                    style={{ background: '#1E3A8A', color: 'white', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                  >
                    {passwordLoading
                      ? <><div className="w-4 h-4 rounded-full border-2 border-white/30 border-t-white animate-spin"></div> جاري التحديث...</>
                      : 'تحديث كلمة المرور'
                    }
                  </button>
                </div>
              </div>
            </div>
          )}

        </div>
      </div>
    </DashboardShell>
  );
}