'use client';

import Link from 'next/link';
import { Skeleton } from 'primereact/skeleton';

interface HomeData {
  recent_trips?: Record<string, unknown>[];
}

function str(obj: Record<string, unknown>, keys: string[]): string {
  for (const k of keys) {
    const v = obj[k];
    if (typeof v === 'string' && v) return v;
    if (typeof v === 'number') return String(v);
  }
  return '';
}

function num(obj: Record<string, unknown>, keys: string[]): number {
  for (const k of keys) {
    const v = obj[k];
    if (typeof v === 'number') return v;
    if (typeof v === 'string' && v) { const n = Number(v); if (!isNaN(n)) return n; }
  }
  return 0;
}

function statusStyle(raw: string): { label: string; color: string; bg: string } {
  const s = raw.toLowerCase();
  if (/مكتمل|complet|done|finished/.test(s)) return { label: 'مكتملة', color: '#059669', bg: '#DCFCE7' };
  if (/متأخر|late|delay/.test(s))            return { label: 'متأخرة', color: '#D97706', bg: '#FEF3C7' };
  if (/جار|ongoing|active|progress/.test(s)) return { label: 'جارية',  color: '#1E3A8A', bg: '#EEF2FF' };
  if (/قادم|upcom|schedul|pending/.test(s))  return { label: 'قادمة',  color: '#7C3AED', bg: '#EDE9FE' };
  if (/ملغ|cancel/.test(s))                  return { label: 'ملغاة',  color: '#EF4444', bg: '#FEE2E2' };
  return { label: raw || '—', color: '#64748B', bg: '#F1F5F9' };
}

function mapTrip(t: Record<string, unknown>, i: number) {
  const id      = str(t, ['id', 'trip_number', 'code']) || String(i + 1);
  const route   = str(t, ['route', 'route_name', 'path_name', 'title']);
  const drvObj  = t.driver && typeof t.driver === 'object' ? t.driver as Record<string, unknown> : null;
  const driver  = drvObj ? str(drvObj, ['name', 'full_name']) : str(t, ['driver_name']);
  const busObj  = t.bus && typeof t.bus === 'object' ? t.bus as Record<string, unknown> : null;
  const busName = busObj ? str(busObj, ['name', 'label']) : str(t, ['bus_name', 'bus']);
  const busPlate= busObj ? str(busObj, ['plate', 'plate_number']) : '';
  const bus     = busName && busPlate ? `${busName} - ${busPlate}` : busName || busPlate || '—';
  const time    = str(t, ['time', 'departure_time', 'start_time', 'scheduled_time']);
  const passengers = num(t, ['passengers', 'passengers_count', 'seats_taken']);
  const st      = statusStyle(str(t, ['status', 'state', 'trip_status']));
  return { id, route, driver, bus, time, passengers, ...st };
}

export default function RecentTrips({ loading, data }: { loading: boolean; data: HomeData }) {
  const header = (
    <div className="flex items-center justify-between px-6 py-4 border-b" style={{ borderColor: '#F1F5F9' }}>
      <div className="flex items-center gap-2">
        <div className="w-8 h-8 rounded-xl flex items-center justify-center" style={{ background: '#EEF2FF' }}>
          <i className="ri-route-fill text-base" style={{ color: '#1E3A8A' }}></i>
        </div>
        <h3 className="font-bold text-slate-800 text-sm" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>آخر الرحلات</h3>
      </div>
      <Link href="/dashboard/trips">
        <button className="text-xs font-semibold cursor-pointer whitespace-nowrap" style={{ color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
          عرض الكل <i className="ri-arrow-left-s-line"></i>
        </button>
      </Link>
    </div>
  );

  if (loading) {
    return (
      <div className="bg-white rounded-2xl overflow-hidden" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
        {header}
        <div className="p-5 space-y-3">
          {[0,1,2,3,4].map(i => <Skeleton key={i} width="100%" height="2.75rem" borderRadius="12px" />)}
        </div>
      </div>
    );
  }

  const trips = (data.recent_trips ?? []).map(mapTrip);
  const cols  = ['رقم الرحلة','المسار','السائق','الباص','الوقت','الراكبات','الحالة'];

  return (
    <div className="bg-white rounded-2xl overflow-hidden" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
      {header}
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead>
            <tr style={{ background: '#F8FAFC' }}>
              {cols.map(h => (
                <th key={h} className="text-right px-5 py-3 text-xs font-bold text-slate-500 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {trips.length === 0 ? (
              <tr>
                <td colSpan={7} className="px-5 py-8 text-center text-sm text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  لا توجد رحلات حديثة
                </td>
              </tr>
            ) : trips.map((t, i) => (
              <tr key={i} className="border-t hover:bg-slate-50 transition-colors cursor-pointer" style={{ borderColor: '#F8FAFC' }}>
                <td className="px-5 py-3.5">
                  <span className="text-xs font-bold" style={{ color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{t.id}</span>
                </td>
                <td className="px-5 py-3.5">
                  <span className="text-xs text-slate-700 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{t.route || '—'}</span>
                </td>
                <td className="px-5 py-3.5">
                  <span className="text-xs text-slate-600 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{t.driver || '—'}</span>
                </td>
                <td className="px-5 py-3.5">
                  <span className="text-xs text-slate-500 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{t.bus}</span>
                </td>
                <td className="px-5 py-3.5">
                  <span className="text-xs text-slate-600 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{t.time || '—'}</span>
                </td>
                <td className="px-5 py-3.5">
                  <div className="flex items-center gap-1">
                    <i className="ri-group-fill text-xs" style={{ color: '#94a3b8' }}></i>
                    <span className="text-xs text-slate-600" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{t.passengers}</span>
                  </div>
                </td>
                <td className="px-5 py-3.5">
                  <span className="px-2.5 py-1 rounded-full text-xs font-bold whitespace-nowrap" style={{ background: t.bg, color: t.color, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                    {t.label}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
