'use client';

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

import 'primereact/resources/themes/lara-light-blue/theme.css';
import 'primereact/resources/primereact.min.css';

// ─── Types ────────────────────────────────────────────────────────────────────

type ApiStatus = 'today' | 'yesterday' | 'ongoing' | 'completed' | 'late' | 'upcoming' | 'cancelled';

interface ApiTripBusType { id: number; name: string }

interface ApiTripBus {
  id: number;
  display_code: string;
  plate: string;
  plate_letters: string;
  plate_numbers: number;
  capacity: number;
  type: ApiTripBusType;
}

interface ApiTripCaptain { id: number; name: string }
interface ApiTripPath    { id: number; description: string }

interface ApiTrip {
  id: number;
  display_code: string;
  path_id: number;
  path: ApiTripPath;
  trip_date: string;
  status: string;
  display_status: string;
  trip_leg: 'go' | 'return';
  shift_label: string;
  planned_start: string;
  planned_end: string;
  actual_start: string | null;
  actual_end: string | null;
  bus: ApiTripBus | null;
  captain: ApiTripCaptain | null;
  boarded_count: number;
  expected_riders_count: number;
  boarding_progress_percent: number;
}

interface ApiTripsResponse {
  key: string;
  msg: string;
  data: {
    data: ApiTrip[];
    pagination: {
      total_items: number;
      count_items: number;
      per_page: number;
      total_pages: number;
      current_page: number;
      next_page_url: string;
      perv_page_url: string;
    };
  };
}

// ─── Status config ────────────────────────────────────────────────────────────

const STATUS_CONFIG: Record<string, { label: string; color: string; bg: string; icon: string }> = {
  today:     { label: 'اليوم',   color: '#1E3A8A', bg: '#EEF2FF',  icon: 'ri-calendar-event-fill' },
  yesterday: { label: 'أمس',     color: '#475569', bg: '#F1F5F9',  icon: 'ri-calendar-line' },
  ongoing:   { label: 'جارية',   color: '#7C3AED', bg: '#EDE9FE',  icon: 'ri-loader-4-fill' },
  completed: { label: 'مكتملة',  color: '#059669', bg: '#DCFCE7',  icon: 'ri-checkbox-circle-fill' },
  late:      { label: 'متأخرة',  color: '#D97706', bg: '#FEF3C7',  icon: 'ri-time-fill' },
  upcoming:  { label: 'قادمة',   color: '#0891B2', bg: '#ECFEFF',  icon: 'ri-calendar-schedule-fill' },
  cancelled: { label: 'ملغاة',   color: '#EF4444', bg: '#FEE2E2',  icon: 'ri-close-circle-fill' },
  scheduled: { label: 'مجدولة',  color: '#64748B', bg: '#F8FAFC',  icon: 'ri-calendar-check-line' },
  in_progress: { label: 'جارية', color: '#7C3AED', bg: '#EDE9FE',  icon: 'ri-loader-4-fill' },
};

const FILTER_STATUSES: ApiStatus[] = ['today', 'yesterday', 'ongoing', 'completed', 'late', 'upcoming', 'cancelled'];

// ─── Helpers ──────────────────────────────────────────────────────────────────

function formatTime(iso: string | null): string {
  if (!iso) return '—';
  try {
    return new Date(iso).toLocaleTimeString('ar-SA', { hour: '2-digit', minute: '2-digit', hour12: true });
  } catch { return iso; }
}

function formatDate(dateStr: string): string {
  try {
    return new Date(dateStr).toLocaleDateString('ar-SA', { day: 'numeric', month: 'short' });
  } catch { return dateStr; }
}

function getDisplayStatus(trip: ApiTrip) {
  return STATUS_CONFIG[trip.display_status] ?? STATUS_CONFIG[trip.status] ?? { label: trip.display_status, color: '#64748B', bg: '#F1F5F9', icon: 'ri-question-line' };
}

// ─── Table Skeleton ───────────────────────────────────────────────────────────

function TableSkeleton() {
  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)' }}>
      <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>
          {Array.from({ length: 6 }).map((_, i) => (
            <tr key={i} className="border-t" style={{ borderColor: '#F8FAFC' }}>
              {Array.from({ length: cols.length }).map((__, j) => (
                <td key={j} className="px-5 py-3.5">
                  <Skeleton width={j === cols.length - 1 ? '60px' : j === 0 ? '60px' : '90%'} height="14px" borderRadius="6px" />
                  {j === 0 && <Skeleton width="40px" height="10px" borderRadius="4px" className="mt-1" />}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ─── Main Page ────────────────────────────────────────────────────────────────

export default function TripsPage() {
  const router = useRouter();
  const toast = useRef<Toast>(null);
  const hasHydrated = useAuthStore((s) => s._hasHydrated);
  const token = useAuthStore((s) => s.token);

  // ── Trips list state ──
  const [trips, setTrips] = useState<ApiTrip[]>([]);
  const [tripsLoading, setTripsLoading] = useState(false);
  const [pagination, setPagination] = useState<ApiTripsResponse['data']['pagination'] | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [statusFilter, setStatusFilter] = useState<ApiStatus>('today');
  const [search, setSearch] = useState('');

  const { request: fetchTripsRaw } = useApi<ApiTripsResponse>();

  // ── Fetch trips ───────────────────────────────────────────────────────────
  const fetchTrips = useCallback(async (page = 1, status: ApiStatus = 'today') => {
    setTripsLoading(true);
    const res = await fetchTripsRaw(`trips?paginate=15&status=${status}&page=${page}`);
    if (res?.data?.data) {
      setTrips(res.data.data);
      setPagination(res.data.pagination);
    } else {
      setTrips([]);
      setPagination(null);
    }
    setTripsLoading(false);
  }, [fetchTripsRaw]);

  useEffect(() => {
    if (!hasHydrated || !token) return;
    void fetchTrips(currentPage, statusFilter);
  }, [hasHydrated, token, currentPage, statusFilter, fetchTrips]);

  // ── Derived ───────────────────────────────────────────────────────────────
  const totalItems   = pagination?.total_items ?? 0;
  const totalPages   = pagination?.total_pages ?? 1;

  const filteredTrips = trips.filter(t =>
    t.path?.description?.includes(search) ||
    t.captain?.name?.includes(search) ||
    t.display_code?.includes(search) ||
    t.bus?.plate?.includes(search)
  );

  const ongoingCount   = trips.filter(t => ['ongoing', 'in_progress'].includes(t.display_status)).length;
  const completedCount = trips.filter(t => t.display_status === 'completed').length;
  const lateCount      = trips.filter(t => t.display_status === 'late').length;

  // ─── Render ───────────────────────────────────────────────────────────────
  return (
    <DashboardShell title="إدارة الرحلات" subtitle={`${totalItems} رحلة مسجلة`}>
      <AppToast ref={toast} position="top-right" />

      {/* Stats */}
      <div className="grid grid-cols-4 gap-4 mb-6">
        {[
          { label: 'إجمالي الرحلات', value: totalItems,    icon: 'ri-calendar-event-fill',  color: '#1E3A8A', bg: '#EEF2FF' },
          { label: 'مكتملة',         value: completedCount, icon: 'ri-checkbox-circle-fill', color: '#059669', bg: '#DCFCE7' },
          { label: 'جارية الآن',     value: ongoingCount,   icon: 'ri-loader-4-fill',        color: '#7C3AED', bg: '#EDE9FE' },
          { label: 'متأخرة',         value: lateCount,      icon: 'ri-time-fill',            color: '#D97706', bg: '#FEF3C7' },
        ].map((s, i) => (
          <div key={i} className="bg-white rounded-2xl p-4 flex items-center gap-3" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
            <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: s.bg }}>
              <i className={`${s.icon} text-xl`} style={{ color: s.color }}></i>
            </div>
            <div>
              {tripsLoading
                ? <Skeleton width="36px" height="28px" borderRadius="8px" className="mb-1" />
                : <p className="text-2xl font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.value}</p>
              }
              <p className="text-xs text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.label}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Toolbar */}
      <div className="flex items-center justify-between mb-5 flex-wrap gap-3">
        <div className="flex items-center gap-3 flex-wrap">
          {/* Search */}
          <div className="relative">
            <input
              type="text"
              placeholder="بحث بالمسار أو السائق أو الرقم..."
              value={search}
              onChange={e => setSearch(e.target.value)}
              className="h-10 bg-white border border-slate-200 rounded-xl pr-10 pl-4 text-sm outline-none text-slate-700"
              style={{ width: '280px', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
            />
            <div className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center">
              <i className="ri-search-line text-slate-400 text-sm"></i>
            </div>
          </div>

          {/* Status filter */}
          <div className="flex items-center gap-2 flex-wrap">
            {FILTER_STATUSES.map(s => {
              const sc = STATUS_CONFIG[s];
              const isActive = statusFilter === s;
              return (
                <button
                  key={s}
                  onClick={() => { setStatusFilter(s); setCurrentPage(1); }}
                  className="px-3 py-2 rounded-xl text-xs font-bold cursor-pointer transition-all whitespace-nowrap flex items-center gap-1.5"
                  style={{
                    background: isActive ? sc.bg : 'white',
                    color: isActive ? sc.color : '#64748b',
                    border: `1px solid ${isActive ? sc.color : '#E2E8F0'}`,
                    fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                  }}
                >
                  <i className={`${sc.icon} text-xs`}></i>
                  {sc.label}
                </button>
              );
            })}
          </div>
        </div>
      </div>

      {/* Table */}
      {tripsLoading ? (
        <TableSkeleton />
      ) : (
        <div className="bg-white rounded-2xl overflow-hidden" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
          <table className="w-full">
            <thead>
              <tr style={{ background: '#F8FAFC' }}>
                {['رقم الرحلة', 'المسار', 'السائق', 'الباص', 'التاريخ', 'الوقت', 'الراكبات', 'الحالة', ''].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>
              {filteredTrips.length === 0 ? (
                <tr>
                  <td colSpan={9} className="text-center py-16">
                    <div className="flex flex-col items-center gap-2">
                      <i className="ri-calendar-line text-4xl text-slate-200"></i>
                      <p className="text-sm text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>لا توجد رحلات</p>
                    </div>
                  </td>
                </tr>
              ) : filteredTrips.map((t) => {
                const sc = getDisplayStatus(t);
                return (
                  <tr
                    key={t.id}
                    onClick={() => router.push(`/dashboard/trips/${t.id}`)}
                    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 block" style={{ color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{t.display_code}</span>
                      <span className="text-[10px] text-slate-400 block" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        {t.trip_leg === 'go' ? '↑ ذهاب' : '↓ عودة'} · {t.shift_label}
                      </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.path?.description ?? '—'}
                      </span>
                    </td>

                    {/* السائق */}
                    <td className="px-5 py-3.5">
                      {t.captain ? (
                        <div className="flex items-center gap-1.5">
                          <div className="w-5 h-5 rounded-full flex items-center justify-center flex-shrink-0" style={{ background: '#EEF2FF' }}>
                            <i className="ri-user-line text-[10px]" style={{ color: '#1E3A8A' }}></i>
                          </div>
                          <span className="text-xs text-slate-600 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{t.captain.name}</span>
                        </div>
                      ) : (
                        <span className="text-xs text-slate-300" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>—</span>
                      )}
                    </td>

                    {/* الباص */}
                    <td className="px-5 py-3.5">
                      {t.bus ? (
                        <div>
                          <span className="text-xs font-bold text-slate-700 block" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{t.bus.display_code}</span>
                          <span className="text-[10px] text-slate-400 block whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{t.bus.plate}</span>
                        </div>
                      ) : (
                        <span className="text-xs text-slate-300">—</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' }}>
                        {formatDate(t.trip_date)}
                      </span>
                    </td>

                    {/* الوقت */}
                    <td className="px-5 py-3.5">
                      <div>
                        <span className="text-xs text-slate-600 block whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                          {formatTime(t.planned_start)}
                        </span>
                        <span className="text-[10px] text-slate-400 block whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                          ← {formatTime(t.planned_end)}
                        </span>
                      </div>
                    </td>

                    {/* الراكبات */}
                    <td className="px-5 py-3.5">
                      <div className="flex items-center gap-1.5">
                        <div className="w-16 h-1.5 bg-slate-100 rounded-full overflow-hidden">
                          <div
                            className="h-full rounded-full transition-all"
                            style={{
                              width: `${t.boarding_progress_percent}%`,
                              background: t.boarding_progress_percent >= 90 ? '#059669' : t.boarding_progress_percent >= 50 ? '#1E3A8A' : '#94a3b8',
                            }}
                          />
                        </div>
                        <span className="text-xs text-slate-600 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                          {t.boarded_count}/{t.expected_riders_count}
                        </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: sc.bg, color: sc.color, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                      >
                        {sc.label}
                      </span>
                    </td>

                    {/* Actions */}
                    <td className="px-5 py-3.5" onClick={e => e.stopPropagation()}>
                      <Link href={`/dashboard/trips/${t.id}`}>
                        <div className="w-7 h-7 rounded-lg flex items-center justify-center cursor-pointer hover:bg-slate-100">
                          <i className="ri-eye-line text-slate-500 text-sm"></i>
                        </div>
                      </Link>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between px-5 py-3 border-t" style={{ borderColor: '#F1F5F9' }}>
              <p className="text-xs text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                صفحة {currentPage} من {totalPages} · {totalItems} رحلة
              </p>
              <div className="flex items-center gap-2">
                <button
                  disabled={currentPage === 1}
                  onClick={() => setCurrentPage(p => p - 1)}
                  className="w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer disabled:opacity-40 hover:bg-slate-100 transition-colors"
                  style={{ border: '1px solid #E2E8F0' }}
                >
                  <i className="ri-arrow-right-s-line text-slate-500"></i>
                </button>
                {Array.from({ length: Math.min(totalPages, 7) }, (_, i) => {
                  let page = i + 1;
                  if (totalPages > 7) {
                    const start = Math.max(1, currentPage - 3);
                    page = start + i;
                    if (page > totalPages) return null;
                  }
                  return (
                    <button
                      key={page}
                      onClick={() => setCurrentPage(page)}
                      className="w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer text-xs font-bold transition-colors"
                      style={{
                        background: currentPage === page ? '#1E3A8A' : 'white',
                        color: currentPage === page ? 'white' : '#64748b',
                        border: `1px solid ${currentPage === page ? '#1E3A8A' : '#E2E8F0'}`,
                        fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                      }}
                    >
                      {page}
                    </button>
                  );
                })}
                <button
                  disabled={currentPage === totalPages}
                  onClick={() => setCurrentPage(p => p + 1)}
                  className="w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer disabled:opacity-40 hover:bg-slate-100 transition-colors"
                  style={{ border: '1px solid #E2E8F0' }}
                >
                  <i className="ri-arrow-left-s-line text-slate-500"></i>
                </button>
              </div>
            </div>
          )}
        </div>
      )}
    </DashboardShell>
  );
}