'use client';

import { useState, useRef } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { AppToast } from '@/app/components/AppToast';
import type { Toast } from 'primereact/toast';
import { useApi } from '@/hooks/useApi';
import { useAuthStore } from '@/store/authStore';

interface DashboardLoginCompanyPayload {
  id?: number;
  name?: string;
  phone?: string;
  country_code?: string;
  full_phone?: string;
  city_id?: number | null;
  city_name?: string | null;
  commercial_register_number?: string | null;
  email?: string;
  image?: string;
  is_active?: boolean;
  is_approved?: boolean;
  is_blocked?: boolean;
  status?: string;
  token?: string;
}

interface LoginResponse {
  key?: string;
  status?: string;
  msg?: string;
  message?: string;
  token?: string;
  data?: DashboardLoginCompanyPayload;
}

export default function DashboardLogin() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPass, setShowPass] = useState(false);
  const router = useRouter();
  const toast = useRef<Toast>(null);
  const { loading, request, lastError } = useApi<LoginResponse>();

  const valid = email.trim() && password.trim();

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

    const result = await request('/auth/login', {
      method: 'POST',
      body: { email: email.trim(), password } as unknown,
      skipAuth: true,
    });

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

    const success =
      result.key === 'success' ||
      String(result.status).toLowerCase() === 'success';

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

    const d = result.data;
    const bearer =
      typeof result.token === 'string'
        ? result.token
        : typeof d?.token === 'string'
          ? d.token
          : '';

    if (!d || d.id === undefined) {
      toast.current?.show({
        severity: 'error',
        summary: 'خطأ',
        detail: result.msg || 'بيانات الاستجابة غير مكتملة',
        life: 4000,
      });
      return;
    }

    useAuthStore.getState().login(
      'dashboard',
      {
        id: d.id,
        companyId: String(d.id),
        name: d.name,
        companyName: d.name,
        email: d.email,
        phone: d.phone,
        country_code: d.country_code,
        full_phone: d.full_phone,
        image: d.image,
        avatar: d.image,
        city_id: d.city_id,
        city_name: d.city_name,
        commercial_register_number: d.commercial_register_number,
        is_active: d.is_active,
        is_approved: d.is_approved,
        is_blocked: d.is_blocked,
        status: d.status,
      },
      bearer
    );

    toast.current?.show({
      severity: 'success',
      summary: 'نجاح',
      detail: result.msg || 'تم تسجيل الدخول بنجاح',
      life: 4000,
    });
    router.push('/dashboard/home');
  }

  return (
    <>
      <AppToast ref={toast} />
      <div className="min-h-screen w-full flex" dir="rtl" style={{ background: '#F0F4FF', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
        {/* Left Panel - Illustration */}
        <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>
          <img src="https://readdy.ai/api/search-image?query=modern%20Saudi%20Arabia%20city%20transportation%20bus%20fleet%20management%20dashboard%20analytics%20professional%20business%20illustration%20deep%20navy%20blue%20background%20with%20glowing%20data%20charts%20routes%20maps%20clean%20minimal%20design&width=800&height=900&seq=dash-login-bg-01&orientation=portrait" alt="" className="absolute inset-0 w-full h-full object-cover object-center opacity-30" />
          <div className="relative z-10 flex flex-col justify-center px-16 py-12">
            <div className="flex items-center gap-3 mb-12">
              <div className="w-12 h-12 rounded-2xl flex items-center justify-center shadow-lg" style={{ background: 'rgba(255,255,255,0.2)' }}>
                <i className="ri-bus-2-fill text-white text-2xl"></i>
              </div>
              <span className="text-white text-2xl font-black">باصاتي</span>
            </div>
            <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 mb-10">
              إدارة متكاملة للباصات والسائقين<br />والرحلات والاشتراكات من مكان واحد
            </p>
            <div className="space-y-4">
              {[
                { icon: 'ri-bus-2-fill', text: 'إدارة أسطول الباصات بالكامل' },
                { icon: 'ri-steering-2-fill', text: 'متابعة السائقين والكابتنات' },
                { icon: 'ri-route-fill', text: 'تتبع الرحلات لحظة بلحظة' },
                { icon: 'ri-bar-chart-2-fill', text: 'تقارير وإحصائيات تفصيلية' },
              ].map((f, i) => (
                <div key={i} className="flex items-center gap-3">
                  <div className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: 'rgba(255,255,255,0.15)' }}>
                    <i className={`${f.icon} text-white text-base`}></i>
                  </div>
                  <span className="text-blue-100 text-sm">{f.text}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Right Panel - Form */}
        <div className="flex-1 flex items-center justify-center px-6 py-12">
          <div className="w-full max-w-md">
            {/* Mobile Logo */}
            <div className="flex items-center gap-3 mb-8 lg:hidden">
              <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: '#1E3A8A' }}>
                <i className="ri-bus-2-fill text-white text-xl"></i>
              </div>
              <span className="text-slate-900 text-xl font-black">باصاتي</span>
            </div>

            <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 className="space-y-5">
                {/* Email field */}
                <div>
                  <label className="block text-sm font-semibold text-slate-600 mb-2">البريد الإلكتروني</label>
                  <div className="relative">
                    <input
                      type="email"
                      value={email}
                      onChange={e => setEmail(e.target.value)}
                      placeholder="company@example.com"
                      className="w-full h-12 bg-slate-50 border border-slate-200 rounded-xl pr-11 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 className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center">
                      <i className="ri-mail-line text-slate-400 text-base"></i>
                    </div>
                  </div>
                </div>


                {/* Password field */}
                <div>
                  <label className="block text-sm font-semibold text-slate-600 mb-2">كلمة المرور</label>
                  <div className="relative">
                    <input
                      type={showPass ? 'text' : 'password'}
                      value={password}
                      onChange={e => setPassword(e.target.value)}
                      placeholder="••••••••"
                      className="w-full h-12 bg-slate-50 border border-slate-200 rounded-xl px-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'}
                    />
                    <button
                      onClick={() => setShowPass(!showPass)}
                      className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center cursor-pointer"
                    >
                      <i className={`${showPass ? 'ri-eye-line' : 'ri-eye-off-line'} text-slate-400 text-base`}></i>
                    </button>
                  </div>
                  <div className="text-left mt-2">
                    <button
                      onClick={() => router.push('/dashboard/forget-password')}
                      className="text-xs font-semibold cursor-pointer"
                      style={{ color: '#1E3A8A' }}
                    >
                      نسيت كلمة المرور؟
                    </button>
                  </div>
                </div>
              </div>

              <button
                onClick={handleLogin}
                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 ? (
                  <><i className="ri-loader-4-line animate-spin text-base"></i> جاري الدخول...</>
                ) : (
                  <><i className="ri-login-box-line text-base"></i> تسجيل الدخول</>
                )}
              </button>
            </div>

            <p className="text-center text-sm text-slate-500 mt-6">
              ليس لديك حساب؟{' '}
              <Link href="/register" className="font-bold cursor-pointer" style={{ color: '#1E3A8A' }}>
                سجّل الآن
              </Link>
            </p>
          </div>
        </div>
      </div>
    </>
  );
}
