'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import LiveMap from './LiveMap';
import StopsTimeline from './StopsTimeline';
import StopPassengersSheet from './StopPassengersSheet';

const stopsPassengers: Record<number, { id: number; name: string; phone: string; avatar: string; status: 'pending' | 'boarded' | 'absent' }[]> = {
  0: [
    { id: 1, name: 'سارة أحمد العتيبي', phone: '0501234567', avatar: 'https://readdy.ai/api/search-image?query=young%20saudi%20female%20student%20smiling%20portrait%20hijab%20neutral%20background%20professional%20photo&width=80&height=80&seq=pax01&orientation=squarish', status: 'pending' },
    { id: 2, name: 'نورة محمد الشمري', phone: '0509876543', avatar: 'https://readdy.ai/api/search-image?query=young%20saudi%20female%20student%20portrait%20hijab%20soft%20background%20professional%20photo&width=80&height=80&seq=pax02&orientation=squarish', status: 'pending' },
    { id: 3, name: 'ريم عبدالله القحطاني', phone: '0551122334', avatar: 'https://readdy.ai/api/search-image?query=young%20female%20student%20smiling%20portrait%20hijab%20light%20background&width=80&height=80&seq=pax03&orientation=squarish', status: 'pending' },
  ],
  1: [
    { id: 4, name: 'لمى خالد الدوسري', phone: '0561234567', avatar: 'https://readdy.ai/api/search-image?query=young%20saudi%20female%20student%20portrait%20hijab%20clean%20background&width=80&height=80&seq=pax04&orientation=squarish', status: 'pending' },
    { id: 5, name: 'هند سعد الزهراني', phone: '0571234567', avatar: 'https://readdy.ai/api/search-image?query=young%20female%20student%20smiling%20hijab%20portrait%20neutral%20background&width=80&height=80&seq=pax05&orientation=squarish', status: 'pending' },
    { id: 6, name: 'منى فهد الحربي', phone: '0581234567', avatar: 'https://readdy.ai/api/search-image?query=young%20saudi%20female%20student%20portrait%20soft%20light%20background%20hijab&width=80&height=80&seq=pax06&orientation=squarish', status: 'pending' },
    { id: 7, name: 'دانة عمر المطيري', phone: '0591234567', avatar: 'https://readdy.ai/api/search-image?query=young%20female%20student%20portrait%20hijab%20white%20background%20professional&width=80&height=80&seq=pax07&orientation=squarish', status: 'pending' },
  ],
  2: [
    { id: 8, name: 'غدير ناصر العنزي', phone: '0501112233', avatar: 'https://readdy.ai/api/search-image?query=young%20saudi%20female%20student%20smiling%20portrait%20hijab%20light%20background&width=80&height=80&seq=pax08&orientation=squarish', status: 'pending' },
    { id: 9, name: 'شهد يوسف البقمي', phone: '0502223344', avatar: 'https://readdy.ai/api/search-image?query=young%20female%20student%20portrait%20hijab%20neutral%20background%20professional%20photo&width=80&height=80&seq=pax09&orientation=squarish', status: 'pending' },
    { id: 10, name: 'رهف علي السبيعي', phone: '0503334455', avatar: 'https://readdy.ai/api/search-image?query=young%20saudi%20female%20student%20portrait%20soft%20background%20hijab%20smiling&width=80&height=80&seq=pax10&orientation=squarish', status: 'pending' },
  ],
  3: [
    { id: 11, name: 'جواهر طلال الرشيدي', phone: '0504445566', avatar: 'https://readdy.ai/api/search-image?query=young%20female%20student%20portrait%20hijab%20clean%20white%20background&width=80&height=80&seq=pax11&orientation=squarish', status: 'pending' },
    { id: 12, name: 'بسمة حمد الغامدي', phone: '0505556677', avatar: 'https://readdy.ai/api/search-image?query=young%20saudi%20female%20student%20smiling%20hijab%20portrait%20neutral%20background&width=80&height=80&seq=pax12&orientation=squarish', status: 'pending' },
  ],
};

const initialStops = [
  { name: 'حي النزهة', time: '7:10 ص', status: 'passed' as const, passengers: 3 },
  { name: 'حي الروضة', time: '7:20 ص', status: 'passed' as const, passengers: 4 },
  { name: 'حي العليا', time: '7:30 ص', status: 'current' as const, passengers: 3 },
  { name: 'حي الملز', time: '7:40 ص', status: 'upcoming' as const, passengers: 2 },
  { name: 'جامعة الملك سعود', time: '8:00 ص', status: 'upcoming' as const, passengers: 2 },
];

interface LiveTripClientProps {
  tripId: string;
}

export default function LiveTripClient({ tripId }: LiveTripClientProps) {
  const [stops, setStops] = useState(initialStops);
  const [seconds, setSeconds] = useState(0);
  const [speed, setSpeed] = useState(42);
  const [showEndConfirm, setShowEndConfirm] = useState(false);
  const [showPassedToast, setShowPassedToast] = useState(false);
  const [toastMsg, setToastMsg] = useState('');
  const [activeSheetStopIndex, setActiveSheetStopIndex] = useState<number | null>(null);
  const [confirmedStops, setConfirmedStops] = useState<Set<number>>(new Set([0, 1]));

  const currentStopIndex = stops.findIndex(s => s.status === 'current');
  const totalPassengers = stops.reduce((a, s) => a + s.passengers, 0);
  const onBusPassengers = stops.filter(s => s.status === 'passed').reduce((a, s) => a + s.passengers, 0);
  const isLastStop = currentStopIndex === stops.length - 2;

  useEffect(() => {
    const timer = setInterval(() => setSeconds(s => s + 1), 1000);
    return () => clearInterval(timer);
  }, []);

  useEffect(() => {
    const speedTimer = setInterval(() => {
      setSpeed(35 + Math.floor(Math.random() * 20));
    }, 5000);
    return () => clearInterval(speedTimer);
  }, []);

  const formatTime = (s: number) => {
    const h = Math.floor(s / 3600).toString().padStart(2, '0');
    const m = Math.floor((s % 3600) / 60).toString().padStart(2, '0');
    const sec = (s % 60).toString().padStart(2, '0');
    return `${h}:${m}:${sec}`;
  };

  const handleOpenSheet = (index: number) => {
    setActiveSheetStopIndex(index);
  };

  const handleSheetConfirm = (results: { id: number; status: 'boarded' | 'absent' }[]) => {
    const stopIndex = activeSheetStopIndex!;
    const boardedCount = results.filter(r => r.status === 'boarded').length;
    setStops(prev => {
      const updated = [...prev];
      updated[stopIndex] = { ...updated[stopIndex], passengers: boardedCount };
      return updated;
    });
    setConfirmedStops(prev => new Set([...prev, stopIndex]));
    setActiveSheetStopIndex(null);
    setToastMsg(`تم تسجيل ${boardedCount} راكبة من ${stops[stopIndex].name}`);
    setShowPassedToast(true);
    setTimeout(() => setShowPassedToast(false), 3000);
  };

  const handleMarkPassed = (index: number) => {
    if (!confirmedStops.has(index)) {
      setActiveSheetStopIndex(index);
      return;
    }
    setStops(prev => {
      const updated = [...prev];
      updated[index] = { ...updated[index], status: 'passed' };
      if (index + 1 < updated.length) {
        updated[index + 1] = { ...updated[index + 1], status: 'current' };
      }
      return updated;
    });
    setToastMsg(`تم تسجيل المرور بـ ${stops[index].name}`);
    setShowPassedToast(true);
    setTimeout(() => setShowPassedToast(false), 2500);
  };

  const nextStop = stops.find(s => s.status === 'current') || stops.find(s => s.status === 'upcoming');

  return (
    <div className="min-h-screen" style={{ background: '#EEF2FF', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }} dir="rtl">

      {showPassedToast && (
        <div className="fixed top-4 left-1/2 z-50 -translate-x-1/2 text-white text-sm font-bold px-4 py-2 rounded-full shadow-lg" style={{ background: '#1E3A8A' }}>
          ✓ {toastMsg}
        </div>
      )}

      <div className="sticky top-0 z-40 bg-white shadow-md rounded-b-2xl px-4 py-3 flex items-center justify-between" style={{ borderBottom: '2px solid #E0E7FF' }}>
        <div className="flex items-center gap-2">
          <span className="w-2 h-2 rounded-full animate-pulse" style={{ background: '#6366F1' }}></span>
          <span className="text-sm font-bold text-slate-900">رحلة جارية 🟢</span>
        </div>
        <span className="text-lg font-bold" style={{ color: '#1E3A8A' }} suppressHydrationWarning={true}>
          {formatTime(seconds)}
        </span>
      </div>

      <div className="px-4 pt-4 space-y-4 pb-32">

        <div className="bg-white rounded-2xl p-3 shadow-sm flex items-center justify-between" style={{ border: '1px solid #E0E7FF' }}>
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ background: '#EEF2FF' }}>
              <i className="ri-speed-up-fill text-sm" style={{ color: '#6366F1' }}></i>
            </div>
            <div>
              <p className="text-xs text-slate-400">السرعة</p>
              <p className="text-sm font-bold text-slate-900" suppressHydrationWarning={true}>{speed} كم/س</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ background: '#fef3c7' }}>
              <i className="ri-map-pin-2-fill text-sm text-amber-500"></i>
            </div>
            <div>
              <p className="text-xs text-slate-400">المحطة الحالية</p>
              <p className="text-sm font-bold text-slate-900">{stops.find(s => s.status === 'current')?.name || '—'}</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ background: '#E0E7FF' }}>
              <i className="ri-time-fill text-sm" style={{ color: '#1E3A8A' }}></i>
            </div>
            <div>
              <p className="text-xs text-slate-400">الوصول المتوقع</p>
              <p className="text-sm font-bold text-slate-900">{nextStop?.time || '8:00 ص'}</p>
            </div>
          </div>
        </div>

        <LiveMap currentStopIndex={currentStopIndex >= 0 ? currentStopIndex : 2} />

        <div className="bg-white rounded-2xl p-4 shadow-sm" style={{ border: '1px solid #E0E7FF' }}>
          <div className="flex items-center justify-between mb-2">
            <div className="flex items-center gap-2">
              <div className="w-7 h-7 rounded-lg flex items-center justify-center" style={{ background: '#EEF2FF' }}>
                <i className="ri-map-pin-line text-sm" style={{ color: '#1E3A8A' }}></i>
              </div>
              <div>
                <p className="text-xs text-slate-400">المحطة القادمة</p>
                <p className="text-sm font-bold text-slate-900">{nextStop?.name || 'جامعة الملك سعود'}</p>
              </div>
            </div>
            <span className="text-sm font-bold px-3 py-1 rounded-full" style={{ color: '#1E3A8A', background: '#EEF2FF' }}>
              {nextStop?.time || '8:00 ص'}
            </span>
          </div>

          <div className="flex items-center justify-between mt-3">
            <div className="flex items-center gap-1.5">
              <div className="w-5 h-5 flex items-center justify-center">
                <i className="ri-group-fill text-sm" style={{ color: '#6366F1' }}></i>
              </div>
              <span className="text-xs text-slate-600">{onBusPassengers} من {totalPassengers} راكبة في الباص</span>
            </div>
            <span className="text-xs font-bold" style={{ color: '#1E3A8A' }}>{Math.round((onBusPassengers / totalPassengers) * 100)}%</span>
          </div>
          <div className="mt-1.5 h-1.5 rounded-full overflow-hidden" style={{ background: '#E0E7FF' }}>
            <div
              className="h-full rounded-full transition-all duration-500"
              style={{ width: `${(onBusPassengers / totalPassengers) * 100}%`, background: '#1E3A8A' }}
            ></div>
          </div>
        </div>

        <StopsTimeline
          stops={stops}
          currentStopIndex={currentStopIndex}
          confirmedStops={confirmedStops}
          onMarkPassed={handleMarkPassed}
          onViewPassengers={handleOpenSheet}
        />
      </div>

      <div className="fixed bottom-0 right-0 left-0 bg-white border-t px-4 py-3 space-y-2" style={{ borderColor: '#E0E7FF' }}>
        {isLastStop && (
          <button
            onClick={() => setShowEndConfirm(true)}
            className="w-full h-12 rounded-xl font-bold text-white text-sm cursor-pointer whitespace-nowrap flex items-center justify-center gap-2"
            style={{ background: '#1E3A8A' }}
          >
            <i className="ri-flag-2-fill text-white"></i>
            الوصول للجامعة / إنهاء الرحلة
          </button>
        )}
        <Link
          href={`/captain/trip/${tripId}/delivery`}
          className="w-full h-12 rounded-xl font-bold text-sm cursor-pointer whitespace-nowrap flex items-center justify-center gap-2"
          style={{ background: '#EEF2FF', color: '#1E3A8A' }}
        >
          <i className="ri-check-double-line" style={{ color: '#6366F1' }}></i>
          تأكيد التسليم
        </Link>
      </div>

      {showEndConfirm && (
        <div className="fixed inset-0 z-50 flex items-end" style={{ background: 'rgba(15,23,42,0.5)' }}>
          <div className="w-full bg-white rounded-t-3xl p-6">
            <div className="w-10 h-1 rounded-full mx-auto mb-5" style={{ background: '#C7D2FE' }}></div>
            <div className="text-center mb-5">
              <div className="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-3" style={{ background: '#EEF2FF' }}>
                <i className="ri-flag-2-fill text-2xl" style={{ color: '#1E3A8A' }}></i>
              </div>
              <h3 className="text-lg font-bold text-slate-900 mb-1">إنهاء الرحلة؟</h3>
              <p className="text-sm text-slate-500">هل وصلتم إلى جامعة الملك سعود؟</p>
            </div>
            <div className="flex gap-3">
              <button
                onClick={() => setShowEndConfirm(false)}
                className="flex-1 h-12 rounded-xl font-bold text-sm cursor-pointer whitespace-nowrap"
                style={{ background: '#EEF2FF', color: '#6366F1' }}
              >
                إلغاء
              </button>
              <Link
                href={`/captain/trip/${tripId}/delivery`}
                className="flex-1 h-12 rounded-xl font-bold text-white text-sm cursor-pointer whitespace-nowrap flex items-center justify-center"
                style={{ background: '#1E3A8A' }}
              >
                نعم، إنهاء الرحلة
              </Link>
            </div>
          </div>
        </div>
      )}

      {activeSheetStopIndex !== null && stopsPassengers[activeSheetStopIndex] && (
        <StopPassengersSheet
          stopName={stops[activeSheetStopIndex].name}
          passengers={stopsPassengers[activeSheetStopIndex]}
          onConfirm={handleSheetConfirm}
          onClose={() => setActiveSheetStopIndex(null)}
        />
      )}
    </div>
  );
}
