'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useApi } from '@/hooks/useApi';
import { useAuthStore } from '@/store/authStore';
import { useToastStore } from '@/store/toastStore';

interface ForgetPasswordResponse {
  key?: string;
  status?: string;
  msg?: string;
  message?: string;
}

const RESET_COUNTRY_CODE = '966';

export default function DashboardForgetPassword() {
  const [phone, setPhone] = useState('');
  const router = useRouter();
  const showToast = useToastStore((s) => s.showToast);
  const { loading, request, lastError } = useApi<ForgetPasswordResponse>();

  const valid = phone.trim().length > 0;

  async function handleSendCode() {
    if (!valid) return;

    const normalizedPhone = phone.trim();
    const result = await request('/auth/forget-password/send-code', {
      method: 'POST',
      body: {
        phone: normalizedPhone,
        country_code: RESET_COUNTRY_CODE,
      } as unknown,
      skipAuth: true,
    });

    if (!result) {
      showToast({
        severity: 'error',
        summary: 'خطأ',
        detail: lastError.current || 'حدث خطأ، يرجى المحاولة مجددًا',
        life: 4000,
      });
      return;
    }

    const success = result.key === 'success' || String(result.status).toLowerCase() === 'success';
    const detail = result.msg || result.message || 'تم تنفيذ الطلب';

    showToast({
      severity: success ? 'success' : 'error',
      summary: success ? 'نجاح' : 'خطأ',
      detail,
      life: 4000,
    });

    if (!success) return;

    useAuthStore.getState().setResetPhone(normalizedPhone, RESET_COUNTRY_CODE);
    router.push('/dashboard/forget-password/activation');
  }

  return (
    <div className='container'>
      <div className="min-h-screen flex" dir="rtl" style={{ background: '#F0F4FF', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
        <div className="hidden lg:flex flex-1 relative overflow-hidden" style={{ background: 'linear-gradient(135deg, #172554 0%, #1E3A8A 50%, #3730A3 100%)' }}>
          <div className="absolute inset-0 opacity-20">
            <div className="absolute top-0 left-0 w-96 h-96 rounded-full" style={{ background: '#6366F1', transform: 'translate(-30%,-30%)' }}></div>
            <div className="absolute bottom-0 right-0 w-80 h-80 rounded-full" style={{ background: '#818CF8', transform: 'translate(20%,30%)' }}></div>
            <div className="absolute top-1/2 left-1/2 w-64 h-64 rounded-full" style={{ background: '#A5B4FC', transform: 'translate(-50%,-50%)' }}></div>
          </div>
          <div className="relative z-10 flex flex-col justify-center px-16 py-12">
            <h2 className="text-white text-4xl font-black leading-tight mb-4">
              استعادة<br />
              <span style={{ color: '#A5B4FC' }}>كلمة المرور</span>
            </h2>
            <p className="text-blue-200 text-base leading-relaxed">أدخل رقم الجوال لإرسال رمز التفعيل.</p>
          </div>
        </div>

        <div className="flex-1 flex items-center justify-center px-6 py-12 lg:max-w-lg">
          <div className="w-full max-w-md">
            <div className="mb-8">
              <h1 className="text-3xl font-black text-slate-900 mb-2">نسيت كلمة المرور؟</h1>
              <p className="text-slate-500 text-sm">اكتب رقم الجوال وسنرسل لك كود التفعيل</p>
            </div>

            <div className="bg-white rounded-3xl p-7 shadow-sm" style={{ border: '1px solid #E0E7FF' }}>
              <div>
                <label className="block text-sm font-semibold text-slate-600 mb-2">رقم الجوال</label>
                <div className="relative">
                  <span className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 text-sm font-semibold">+{RESET_COUNTRY_CODE}</span>
                  <input
                    type="tel"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value.replace(/\D/g, ''))}
                    placeholder="5xxxxxxxx"
                    className="w-full h-12 bg-slate-50 border border-slate-200 rounded-xl pr-20 pl-4 text-slate-900 text-sm outline-none transition-all"
                    onFocus={(e) => (e.target.style.boxShadow = '0 0 0 3px #C7D2FE')}
                    onBlur={(e) => (e.target.style.boxShadow = 'none')}
                    dir="ltr"
                  />
                </div>
              </div>

              <button
                onClick={handleSendCode}
                disabled={!valid || loading}
                className="w-full h-12 rounded-xl font-bold text-sm transition-all mt-6 flex items-center justify-center gap-2 whitespace-nowrap"
                style={{
                  background: valid ? '#1E3A8A' : '#E0E7FF',
                  color: valid ? 'white' : '#A5B4FC',
                  cursor: valid ? 'pointer' : 'not-allowed',
                }}
              >
                {loading ? 'جاري الإرسال...' : 'تأكيد'}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
