'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import PassengerCard from './PassengerCard';
import AbsentModal from './absent/AbsentModal';

const tripData = {
  title: 'رحلة الصباح',
  busType: 'باص 14',
  time: '7:30 ص',
  from: 'حي النزهة',
  to: 'جامعة الملك سعود',
  date: 'الثلاثاء، 11 مارس 2026',
  stops: [
    { name: 'حي النزهة', passengers: 2 },
    { name: 'حي الروضة', passengers: 2 },
    { name: 'حي العليا', passengers: 2 },
    { name: 'حي السليمانية', passengers: 2 },
    { name: 'حي الملز', passengers: 2 },
    { name: 'حي الورود', passengers: 2 },
    { name: 'حي النخيل', passengers: 2 },
    { name: 'جامعة الملك سعود', passengers: 0 },
  ],
  passengers: [
    { id: '1', name: 'نورة أحمد العتيبي', pickup: 'حي النزهة', status: 'pending' as const },
    { id: '2', name: 'سارة محمد القحطاني', pickup: 'حي النزهة', status: 'pending' as const },
    { id: '3', name: 'فاطمة عبدالله الدوسري', pickup: 'حي الروضة', status: 'pending' as const },
    { id: '4', name: 'مريم خالد الشمري', pickup: 'حي الروضة', status: 'pending' as const },
    { id: '5', name: 'هند سعد المطيري', pickup: 'حي العليا', status: 'pending' as const },
    { id: '6', name: 'ريم فهد الحربي', pickup: 'حي العليا', status: 'pending' as const },
    { id: '7', name: 'لمى عبدالرحمن الزهراني', pickup: 'حي السليمانية', status: 'pending' as const },
    { id: '8', name: 'جواهر ناصر العنزي', pickup: 'حي السليمانية', status: 'pending' as const },
    { id: '9', name: 'أمل يوسف الغامدي', pickup: 'حي الملز', status: 'pending' as const },
    { id: '10', name: 'شهد إبراهيم الشهري', pickup: 'حي الملز', status: 'pending' as const },
    { id: '11', name: 'رهف عمر البقمي', pickup: 'حي الورود', status: 'pending' as const },
    { id: '12', name: 'دانة سلطان الجهني', pickup: 'حي الورود', status: 'pending' as const },
    { id: '13', name: 'غلا حسن العسيري', pickup: 'حي النخيل', status: 'pending' as const },
    { id: '14', name: 'بشاير راشد القرني', pickup: 'حي النخيل', status: 'pending' as const },
  ],
};

export default function TripDetailsClient({ tripId }: { tripId: string }) {
  const router = useRouter();
  const [passengers, setPassengers] = useState(tripData.passengers as Array<{ id: string; name: string; pickup: string; status: 'pending' | 'picked' | 'absent' }>);
  const [activeTab, setActiveTab] = useState<'passengers' | 'route'>('passengers');
  const [absentModal, setAbsentModal] = useState<{ open: boolean; id: string; name: string; pickup: string }>({
    open: false, id: '', name: '', pickup: '',
  });

  const pickedCount = passengers.filter(p => p.status === 'picked').length;
  const absentCount = passengers.filter(p => p.status === 'absent').length;
  const pendingCount = passengers.filter(p => p.status === 'pending').length;

  const handlePickup = (id: string) => {
    setPassengers(prev => prev.map(p => p.id === id ? { ...p, status: 'picked' as const } : p));
  };

  const handleAbsentRequest = (id: string) => {
    const p = passengers.find(x => x.id === id);
    if (p) setAbsentModal({ open: true, id, name: p.name, pickup: p.pickup });
  };

  const handleAbsentConfirm = (_reason: string) => {
    setPassengers(prev => prev.map(p => p.id === absentModal.id ? { ...p, status: 'absent' as const } : p));
    setAbsentModal({ open: false, id: '', name: '', pickup: '' });
  };

  return (
    <div className="min-h-screen" dir="rtl" style={{ maxWidth: '390px', margin: '0 auto', background: '#F0F4FF' }}>
      <div className="h-11" style={{ background: '#172554' }}></div>

      {/* Header */}
      <header className="h-14 flex items-center justify-center relative" style={{ background: '#172554' }}>
        <button
          onClick={() => router.back()}
          className="absolute right-4 w-9 h-9 rounded-xl flex items-center justify-center cursor-pointer"
          style={{ background: 'rgba(255,255,255,0.15)', border: '1px solid rgba(255,255,255,0.2)' }}
        >
          <i className="ri-arrow-right-s-line text-white text-xl"></i>
        </button>
        <h1 className="text-white text-lg font-bold" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>تفاصيل الرحلة</h1>
        <Link href={`/captain/trip/${tripId}/live`}>
          <button
            className="absolute left-4 h-9 px-3 rounded-xl flex items-center justify-center cursor-pointer gap-1.5"
            style={{ background: 'rgba(255,255,255,0.15)', border: '1px solid rgba(255,255,255,0.2)' }}
          >
            <i className="ri-navigation-fill text-white text-sm"></i>
            <span className="text-white text-xs font-bold" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>مباشر</span>
          </button>
        </Link>
      </header>

      {/* Hero Card */}
      <div className="relative">
        <div className="px-4 pt-5 pb-10 relative overflow-hidden" style={{ background: '#172554' }}>
          <div className="absolute top-0 right-0 w-40 h-40 rounded-full opacity-10" style={{ background: 'white', transform: 'translate(30%,-30%)' }}></div>
          <div className="absolute bottom-0 left-0 w-32 h-32 rounded-full opacity-10" style={{ background: 'white', transform: 'translate(-20%,40%)' }}></div>

          <div className="relative flex items-start justify-between mb-4">
            <div>
              <span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-bold mb-2" style={{ background: 'rgba(255,255,255,0.15)', color: 'white', border: '1px solid rgba(255,255,255,0.25)' }}>
                <span className="w-1.5 h-1.5 rounded-full bg-green-400 animate-pulse"></span>
                جارية الآن
              </span>
              <h2 className="text-white text-xl font-bold" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{tripData.title}</h2>
              <p className="text-xs mt-0.5" style={{ color: '#A5B4FC', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{tripData.date}</p>
            </div>
            <div className="flex flex-col items-center rounded-2xl px-3 py-2" style={{ background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.2)' }}>
              <i className="ri-bus-2-fill text-white text-2xl"></i>
              <span className="text-white text-xs font-bold mt-0.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{tripData.busType}</span>
            </div>
          </div>

          <div className="flex items-center gap-3 rounded-2xl p-3" style={{ background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.15)' }}>
            <div className="flex-1">
              <p className="text-[10px] mb-0.5" style={{ color: '#A5B4FC', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>من</p>
              <p className="text-white text-sm font-bold" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{tripData.from}</p>
            </div>
            <div className="flex flex-col items-center gap-1">
              <div className="w-8 h-8 rounded-full flex items-center justify-center" style={{ background: 'rgba(255,255,255,0.15)' }}>
                <i className="ri-arrow-left-line text-white text-sm"></i>
              </div>
              <span className="text-[9px]" style={{ color: '#A5B4FC', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{tripData.time}</span>
            </div>
            <div className="flex-1 text-left">
              <p className="text-[10px] mb-0.5" style={{ color: '#A5B4FC', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>إلى</p>
              <p className="text-white text-sm font-bold" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{tripData.to}</p>
            </div>
          </div>
        </div>
        <div className="absolute bottom-0 left-0 right-0 h-6 rounded-t-[28px]" style={{ background: '#F0F4FF' }}></div>
      </div>

      {/* Stats */}
      <div className="px-4 -mt-1 mb-4">
        <div className="bg-white rounded-2xl shadow-sm overflow-hidden" style={{ border: '1px solid #E0E7FF' }}>
          <div className="grid grid-cols-3 divide-x divide-slate-100">
            {[
              { label: 'في الباص', value: pickedCount, icon: 'ri-checkbox-circle-fill', color: '#1E3A8A', bg: '#EEF2FF' },
              { label: 'في الانتظار', value: pendingCount, icon: 'ri-time-fill', color: '#d97706', bg: '#fef3c7' },
              { label: 'غائبة', value: absentCount, icon: 'ri-close-circle-fill', color: '#dc2626', bg: '#fee2e2' },
            ].map((s, i) => (
              <div key={i} className="flex flex-col items-center py-3.5 px-2">
                <div className="w-8 h-8 rounded-xl flex items-center justify-center mb-1.5" style={{ background: s.bg }}>
                  <i className={`${s.icon} text-base`} style={{ color: s.color }}></i>
                </div>
                <p className="text-slate-900 text-lg font-bold leading-none" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.value}</p>
                <p className="text-slate-400 text-[10px] mt-0.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.label}</p>
              </div>
            ))}
          </div>
          <div className="px-4 pb-3 pt-1">
            <div className="flex items-center justify-between mb-1.5">
              <p className="text-[11px] text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>نسبة الركوب</p>
              <p className="text-[11px] font-bold" style={{ color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                {Math.round((pickedCount / passengers.length) * 100)}%
              </p>
            </div>
            <div className="h-2 rounded-full overflow-hidden" style={{ background: '#E0E7FF' }}>
              <div
                className="h-full rounded-full transition-all duration-500"
                style={{ width: `${(pickedCount / passengers.length) * 100}%`, background: '#1E3A8A' }}
              ></div>
            </div>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="px-4 mb-3">
        <div className="rounded-2xl p-1 flex gap-1" style={{ background: '#E0E7FF' }}>
          {[
            { id: 'passengers', label: 'قائمة الراكبات', icon: 'ri-group-line' },
            { id: 'route', label: 'نقاط التوقف', icon: 'ri-route-line' },
          ].map(tab => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id as 'passengers' | 'route')}
              className="flex-1 h-10 rounded-xl flex items-center justify-center gap-1.5 text-sm font-bold cursor-pointer transition-all whitespace-nowrap"
              style={{
                fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                background: activeTab === tab.id ? 'white' : 'transparent',
                color: activeTab === tab.id ? '#1E3A8A' : '#818CF8',
                boxShadow: activeTab === tab.id ? '0 1px 4px rgba(30,58,138,0.12)' : 'none',
              }}
            >
              <i className={`${tab.icon} text-base`}></i>
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      {/* Tab Content */}
      <div className="px-4 pb-36">
        {activeTab === 'passengers' && (
          <div className="space-y-2">
            <div className="flex items-center justify-between mb-2">
              <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                إجمالي <span className="font-bold text-slate-700">{passengers.length} راكبة</span>
              </p>
              <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                اسحب لليسار للغياب
              </p>
            </div>
            {passengers.map(passenger => (
              <PassengerCard
                key={passenger.id}
                passenger={passenger}
                onPickup={handlePickup}
                onAbsent={handleAbsentRequest}
              />
            ))}
          </div>
        )}

        {activeTab === 'route' && (
          <div className="bg-white rounded-2xl p-4 shadow-sm" style={{ border: '1px solid #E0E7FF' }}>
            <div className="space-y-0">
              {tripData.stops.map((stop, index) => (
                <div key={index} className="flex items-start gap-3">
                  <div className="flex flex-col items-center">
                    {index === 0 ? (
                      <div className="w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0" style={{ background: '#EEF2FF' }}>
                        <i className="ri-map-pin-2-fill text-base" style={{ color: '#1E3A8A' }}></i>
                      </div>
                    ) : index === tripData.stops.length - 1 ? (
                      <div className="w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0" style={{ background: '#1E3A8A' }}>
                        <i className="ri-flag-2-fill text-white text-base"></i>
                      </div>
                    ) : (
                      <div className="w-5 h-5 rounded-full flex-shrink-0 mt-2 border-2 flex items-center justify-center" style={{ background: '#818CF8', borderColor: '#E0E7FF' }}>
                        <div className="w-2 h-2 rounded-full bg-white"></div>
                      </div>
                    )}
                    {index < tripData.stops.length - 1 && (
                      <div className="w-0.5 h-8 my-1" style={{ background: '#C7D2FE' }}></div>
                    )}
                  </div>
                  <div className="pt-1.5 pb-1 flex-1">
                    <div className="flex items-center justify-between">
                      <p className="text-sm font-bold" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif', color: (index === 0 || index === tripData.stops.length - 1) ? '#1E3A8A' : '#334155' }}>
                        {stop.name}
                      </p>
                      {stop.passengers > 0 && (
                        <span className="text-[10px] font-semibold px-2 py-0.5 rounded-full" style={{ background: '#EEF2FF', color: '#6366F1', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                          {stop.passengers} راكبة
                        </span>
                      )}
                    </div>
                    <p className="text-[10px] text-slate-400 mt-0.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                      {index === 0 ? 'نقطة الانطلاق' : index === tripData.stops.length - 1 ? 'الوجهة النهائية' : 'محطة توقف'}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Bottom CTA */}
      <div
        className="fixed bottom-0 left-0 right-0 bg-white/95 backdrop-blur-sm border-t p-4 z-40"
        style={{ maxWidth: '390px', margin: '0 auto', borderColor: '#E0E7FF', paddingBottom: 'calc(16px + env(safe-area-inset-bottom, 0px))' }}
      >
        <div className="flex items-center gap-2 mb-3 px-1">
          <i className="ri-information-line text-sm" style={{ color: '#818CF8' }}></i>
          <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
            راجع قائمة الراكبات قبل بدء الرحلة
          </p>
        </div>
        <Link href={`/captain/trip/${tripId}/live`}>
          <button
            className="w-full h-[52px] text-white rounded-2xl text-base font-bold whitespace-nowrap cursor-pointer transition-all active:scale-95 shadow-lg flex items-center justify-center gap-2"
            style={{ background: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
          >
            <i className="ri-navigation-fill text-lg"></i>
            بدء الرحلة المباشرة
          </button>
        </Link>
      </div>

      {/* Absent Modal */}
      <AbsentModal
        isOpen={absentModal.open}
        onClose={() => setAbsentModal({ open: false, id: '', name: '', pickup: '' })}
        passengerName={absentModal.name}
        pickupLocation={absentModal.pickup}
        onConfirm={handleAbsentConfirm}
      />
    </div>
  );
}
