'use client';

import { Skeleton } from 'primereact/skeleton';

interface HomeData {
  late_trips_alerts?:       Record<string, unknown>[];
  maintenance_alerts?:      Record<string, unknown>[];
  pending_captain_requests?: Record<string, unknown>[];
  recent_payments?:         Record<string, unknown>[];
}

type UiAlert = { icon: string; color: string; bg: string; title: string; desc: string; time: string };

function s(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 mapAlerts(data: HomeData): UiAlert[] {
  const out: UiAlert[] = [];

  for (const item of data.late_trips_alerts ?? []) {
    out.push({
      icon: 'ri-alert-fill', color: '#D97706', bg: '#FEF3C7',
      title: s(item, ['title']) || 'رحلة متأخرة',
      desc:  s(item, ['message', 'desc', 'description', 'details', 'trip_identifier']) || '—',
      time:  s(item, ['time', 'time_ago', 'created_at_human', 'created_at']) || '',
    });
  }

  for (const item of data.maintenance_alerts ?? []) {
    out.push({
      icon: 'ri-tools-fill', color: '#EF4444', bg: '#FEE2E2',
      title: s(item, ['title']) || 'صيانة مطلوبة',
      desc:  s(item, ['message', 'desc', 'description', 'details', 'bus_name']) || '—',
      time:  s(item, ['time', 'time_ago', 'scheduled_at', 'created_at']) || '',
    });
  }

  for (const item of data.pending_captain_requests ?? []) {
    out.push({
      icon: 'ri-user-add-fill', color: '#1E3A8A', bg: '#EEF2FF',
      title: s(item, ['title']) || 'سائق جديد',
      desc:  s(item, ['message', 'desc', 'description', 'driver_name', 'name']) || '—',
      time:  s(item, ['time', 'time_ago', 'created_at_human', 'created_at']) || '',
    });
  }

  for (const item of data.recent_payments ?? []) {
    out.push({
      icon: 'ri-money-dollar-circle-fill', color: '#059669', bg: '#DCFCE7',
      title: s(item, ['title']) || 'دفعة مستلمة',
      desc:  s(item, ['message', 'desc', 'description', 'details', 'reference']) || '—',
      time:  s(item, ['time', 'time_ago', 'paid_at', 'created_at']) || '',
    });
  }

  return out;
}

export default function AlertsWidget({ loading, data }: { loading: boolean; data: HomeData }) {
  const header = (
    <div className="flex items-center gap-2 px-5 py-4 border-b" style={{ borderColor: '#F1F5F9' }}>
      <div className="w-8 h-8 rounded-xl flex items-center justify-center" style={{ background: '#FEF3C7' }}>
        <i className="ri-notification-3-fill text-base" style={{ color: '#D97706' }}></i>
      </div>
      <h3 className="font-bold text-slate-800 text-sm" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>التنبيهات</h3>
    </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-4 space-y-3">
          {[0,1,2,3].map(i => (
            <div key={i} className="flex items-start gap-3">
              <Skeleton width="2.25rem" height="2.25rem" borderRadius="12px" className="flex-shrink-0" />
              <div className="flex-1 space-y-2 pt-0.5">
                <Skeleton width="50%" height="0.875rem" borderRadius="6px" />
                <Skeleton width="90%" height="0.75rem" borderRadius="6px" />
              </div>
              <Skeleton width="3rem" height="0.625rem" borderRadius="6px" className="mt-1" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  const alerts = mapAlerts(data);

  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>
        {alerts.length === 0 ? (
          <p className="px-5 py-6 text-center text-sm text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>لا توجد تنبيهات</p>
        ) : alerts.map((a, i) => (
          <div key={i} className="flex items-start gap-3 px-5 py-3.5 border-t hover:bg-slate-50 transition-colors cursor-pointer" style={{ borderColor: '#F8FAFC' }}>
            <div className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: a.bg }}>
              <i className={`${a.icon} text-base`} style={{ color: a.color }}></i>
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-bold text-slate-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{a.title}</p>
              <p className="text-xs text-slate-500 mt-0.5 leading-relaxed" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{a.desc}</p>
            </div>
            <span className="text-[10px] text-slate-400 whitespace-nowrap mt-0.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{a.time || '—'}</span>
          </div>
        ))}
      </div>
    </div>
  );
}
