'use client';

import { useState, useEffect, useRef } from 'react';

interface Passenger {
  id: number;
  name: string;
  phone: string;
  avatar: string;
  status: 'pending' | 'boarded' | 'absent';
}

interface StopPassengersSheetProps {
  stopName: string;
  passengers: Passenger[];
  onConfirm: (results: { id: number; status: 'boarded' | 'absent' }[]) => void;
  onClose: () => void;
}

type ScanState = 'idle' | 'scanning' | 'success';

function GlobalQRScanner({
  passengers,
  statuses,
  onBoard,
  onClose,
}: {
  passengers: Passenger[];
  statuses: Record<number, 'pending' | 'boarded' | 'absent'>;
  onBoard: (id: number) => void;
  onClose: () => void;
}) {
  const [scanState, setScanState] = useState<ScanState>('idle');
  const [scanProgress, setScanProgress] = useState(0);
  const [boardedPassenger, setBoardedPassenger] = useState<Passenger | null>(null);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const pendingPassengers = passengers.filter(p => statuses[p.id] === 'pending');

  const startScan = () => {
    setScanState('scanning');
    setScanProgress(0);
    let p = 0;
    intervalRef.current = setInterval(() => {
      p += 3;
      setScanProgress(p);
      if (p >= 100) {
        if (intervalRef.current) clearInterval(intervalRef.current);
        if (pendingPassengers.length > 0) {
          const randomIdx = Math.floor(Math.random() * pendingPassengers.length);
          const matched = pendingPassengers[randomIdx];
          setBoardedPassenger(matched);
          setScanState('success');
          onBoard(matched.id);
        }
      }
    }, 40);
  };

  const resetScan = () => {
    if (intervalRef.current) clearInterval(intervalRef.current);
    setScanState('idle');
    setScanProgress(0);
    setBoardedPassenger(null);
  };

  useEffect(() => () => { if (intervalRef.current) clearInterval(intervalRef.current); }, []);

  return (
    <div className="fixed inset-0 z-[60] flex items-end" style={{ background: 'rgba(0,0,0,0.75)' }}>
      <div className="w-full bg-white rounded-t-3xl" dir="rtl">
        <div className="px-5 pt-4 pb-3 flex items-center justify-between" style={{ borderBottom: '1px solid #E0E7FF' }}>
          <div>
            <h3 className="text-base font-bold text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>سكانر QR Code</h3>
            <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
              {pendingPassengers.length} طالبة لم تُسكن بعد
            </p>
          </div>
          <button onClick={onClose} className="w-8 h-8 rounded-full flex items-center justify-center cursor-pointer" style={{ background: '#EEF2FF' }}>
            <i className="ri-close-line text-sm" style={{ color: '#6366F1' }}></i>
          </button>
        </div>

        <div className="px-5 py-5">
          <div
            className="rounded-2xl overflow-hidden mx-auto"
            style={{
              background: scanState === 'success' ? '#d1fae5' : '#0f172a',
              width: '100%',
              transition: 'background 0.3s ease',
            }}
          >
            <div className="p-4">
              <div
                className="relative mx-auto rounded-xl overflow-hidden flex items-center justify-center"
                style={{ width: '200px', height: '200px', background: scanState === 'success' ? 'transparent' : '#1e293b' }}
              >
                {scanState !== 'success' && (
                  <>
                    <div className="absolute inset-0 opacity-10 grid grid-cols-6 gap-0.5 p-2">
                      {Array.from({ length: 36 }).map((_, i) => (
                        <div key={i} className="rounded-sm" style={{ background: i % 3 === 0 ? '#fff' : 'transparent', aspectRatio: '1' }}></div>
                      ))}
                    </div>
                    <div className="absolute top-2 right-2 w-8 h-8 border-t-2 border-r-2 border-emerald-400 rounded-tr-md"></div>
                    <div className="absolute top-2 left-2 w-8 h-8 border-t-2 border-l-2 border-emerald-400 rounded-tl-md"></div>
                    <div className="absolute bottom-2 right-2 w-8 h-8 border-b-2 border-r-2 border-emerald-400 rounded-br-md"></div>
                    <div className="absolute bottom-2 left-2 w-8 h-8 border-b-2 border-l-2 border-emerald-400 rounded-bl-md"></div>
                    {scanState === 'scanning' && (
                      <div
                        className="absolute left-2 right-2 h-0.5 rounded-full"
                        style={{
                          background: 'linear-gradient(90deg, transparent, #10b981, transparent)',
                          top: `${(scanProgress / 100) * 180 + 10}px`,
                          boxShadow: '0 0 8px #10b981',
                          transition: 'top 0.04s linear',
                        }}
                      ></div>
                    )}
                    <div className="relative z-10 flex flex-col items-center gap-2">
                      <i className={`ri-qr-scan-2-line text-5xl text-emerald-400 ${scanState === 'scanning' ? 'animate-pulse' : ''}`}></i>
                      {scanState === 'idle' && (
                        <span className="text-xs text-slate-400 text-center" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>وجّه الكاميرا على QR Code الطالبة</span>
                      )}
                    </div>
                  </>
                )}

                {scanState === 'success' && boardedPassenger && (
                  <div className="flex flex-col items-center gap-3 p-4">
                    <div className="w-16 h-16 rounded-full overflow-hidden border-4 border-emerald-400">
                      <img src={boardedPassenger.avatar} alt={boardedPassenger.name} className="w-full h-full object-cover object-top" />
                    </div>
                    <div className="w-10 h-10 rounded-full flex items-center justify-center" style={{ background: '#059669' }}>
                      <i className="ri-checkbox-circle-line text-2xl text-white"></i>
                    </div>
                  </div>
                )}
              </div>

              {scanState === 'scanning' && (
                <div className="mt-3">
                  <div className="h-1 rounded-full overflow-hidden" style={{ background: 'rgba(255,255,255,0.1)' }}>
                    <div className="h-full rounded-full" style={{ width: `${scanProgress}%`, background: 'linear-gradient(90deg,#10b981,#34d399)', transition: 'width 0.04s linear' }}></div>
                  </div>
                </div>
              )}
            </div>

            {scanState === 'idle' && pendingPassengers.length > 0 && (
              <div className="px-4 pb-4">
                <button
                  onClick={startScan}
                  className="w-full h-11 rounded-xl font-bold text-sm cursor-pointer whitespace-nowrap flex items-center justify-center gap-2"
                  style={{ background: 'linear-gradient(135deg,#059669,#10b981)', color: 'white', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                >
                  <i className="ri-qr-scan-2-line text-base"></i>
                  ابدأ المسح
                </button>
              </div>
            )}

            {scanState === 'idle' && pendingPassengers.length === 0 && (
              <div className="px-4 pb-4">
                <p className="text-center text-sm font-bold text-emerald-600 py-2" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  تم تسكين جميع الطالبات ✓
                </p>
              </div>
            )}
          </div>

          {scanState === 'success' && boardedPassenger && (
            <div
              className="mt-4 rounded-2xl p-4 flex items-center gap-3"
              style={{ background: '#f0fdf4', border: '2px solid #bbf7d0' }}
            >
              <div className="w-10 h-10 flex items-center justify-center rounded-full flex-shrink-0" style={{ background: '#dcfce7' }}>
                <i className="ri-checkbox-circle-fill text-xl" style={{ color: '#059669' }}></i>
              </div>
              <div>
                <p className="text-sm font-bold" style={{ color: '#065f46', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  الطالبة <span style={{ color: '#059669' }}>{boardedPassenger.name}</span> ركبت
                </p>
                <p className="text-xs mt-0.5" style={{ color: '#6ee7b7', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>تم تسجيل الركوب بنجاح</p>
              </div>
            </div>
          )}

          {scanState === 'success' && (
            <button
              onClick={resetScan}
              className="w-full h-11 rounded-xl font-bold text-sm cursor-pointer whitespace-nowrap mt-3 flex items-center justify-center gap-2"
              style={{ background: '#1E3A8A', color: 'white', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
            >
              <i className="ri-qr-scan-2-line text-base"></i>
              سكان طالبة أخرى
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

export default function StopPassengersSheet({ stopName, passengers, onConfirm, onClose }: StopPassengersSheetProps) {
  const [statuses, setStatuses] = useState<Record<number, 'pending' | 'boarded' | 'absent'>>(
    Object.fromEntries(passengers.map(p => [p.id, p.status]))
  );
  const [showScanner, setShowScanner] = useState(false);

  const boardedCount = Object.values(statuses).filter(s => s === 'boarded').length;
  const absentCount = Object.values(statuses).filter(s => s === 'absent').length;
  const pendingCount = Object.values(statuses).filter(s => s === 'pending').length;

  const handleBoard = (id: number) => {
    setStatuses(prev => ({ ...prev, [id]: 'boarded' }));
  };

  const handleAbsent = (id: number) => {
    setStatuses(prev => ({ ...prev, [id]: 'absent' }));
  };

  const handleConfirm = () => {
    const results = passengers.map(p => ({
      id: p.id,
      status: statuses[p.id] === 'absent' ? 'absent' : 'boarded' as 'boarded' | 'absent',
    }));
    onConfirm(results);
  };

  const statusStyle: Record<string, { border: string; bg: string }> = {
    boarded: { border: '#bbf7d0', bg: '#f0fdf4' },
    absent: { border: '#fecaca', bg: '#fff5f5' },
    pending: { border: '#E0E7FF', bg: '#fafbff' },
  };

  return (
    <>
      <div className="fixed inset-0 z-50 flex items-end" style={{ background: 'rgba(15,23,42,0.55)' }}>
        <div className="w-full bg-white rounded-t-3xl shadow-2xl" style={{ maxHeight: '85vh', display: 'flex', flexDirection: 'column' }} dir="rtl">

          <div className="flex-shrink-0 px-5 pt-4 pb-3" style={{ borderBottom: '1px solid #E0E7FF' }}>
            <div className="w-10 h-1 rounded-full mx-auto mb-4" style={{ background: '#C7D2FE' }}></div>
            <div className="flex items-center justify-between mb-3">
              <div>
                <h2 className="text-base font-bold text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>طالبات المحطة</h2>
                <div className="flex items-center gap-1 mt-0.5">
                  <i className="ri-map-pin-2-fill text-xs" style={{ color: '#1E3A8A' }}></i>
                  <span className="text-sm font-bold" style={{ color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{stopName}</span>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setShowScanner(true)}
                  className="h-9 px-3 rounded-xl flex items-center gap-1.5 font-bold text-xs cursor-pointer whitespace-nowrap"
                  style={{ background: '#1E3A8A', color: 'white', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                >
                  <i className="ri-qr-scan-2-line text-sm"></i>
                  سكانر
                </button>
                <button onClick={onClose} className="w-8 h-8 rounded-full flex items-center justify-center cursor-pointer" style={{ background: '#EEF2FF' }}>
                  <i className="ri-close-line text-sm" style={{ color: '#6366F1' }}></i>
                </button>
              </div>
            </div>

            <div className="flex gap-2">
              {[
                { label: 'إجمالي', val: passengers.length, bg: '#EEF2FF', color: '#1E3A8A' },
                { label: 'ركبت', val: boardedCount, bg: '#dcfce7', color: '#15803d' },
                { label: 'غائبة', val: absentCount, bg: '#fef2f2', color: '#dc2626' },
                { label: 'لم يُحدد', val: pendingCount, bg: '#fef9c3', color: '#d97706' },
              ].map((item, i) => (
                <div key={i} className="flex-1 rounded-xl p-2 text-center" style={{ background: item.bg }}>
                  <p className="text-lg font-bold" style={{ color: item.color, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{item.val}</p>
                  <p className="text-xs" style={{ color: item.color, fontFamily: '"IBM Plex Sans Arabic", sans-serif', opacity: 0.8 }}>{item.label}</p>
                </div>
              ))}
            </div>
          </div>

          <div className="flex-1 overflow-y-auto px-5 py-3 space-y-2.5">
            {passengers.map(p => {
              const s = statuses[p.id];
              const style = statusStyle[s];
              return (
                <div
                  key={p.id}
                  className="flex items-center gap-3 rounded-2xl p-3 transition-all"
                  style={{ border: `1.5px solid ${style.border}`, background: style.bg }}
                >
                  <div className="w-11 h-11 rounded-full overflow-hidden flex-shrink-0 border-2" style={{ borderColor: style.border }}>
                    <img src={p.avatar} alt={p.name} className="w-full h-full object-cover object-top" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-bold text-slate-900 truncate" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{p.name}</p>
                    <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{p.phone}</p>
                  </div>

                  <div className="flex-shrink-0 flex items-center gap-1.5">
                    {s === 'pending' && (
                      <button
                        onClick={() => handleAbsent(p.id)}
                        className="h-8 px-2.5 rounded-xl flex items-center gap-1 font-bold text-xs cursor-pointer whitespace-nowrap"
                        style={{ background: '#fef2f2', color: '#dc2626', border: '1px solid #fecaca', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                      >
                        <i className="ri-close-line text-xs"></i>
                        غياب
                      </button>
                    )}
                    {s === 'boarded' && (
                      <span className="flex items-center gap-1 text-xs font-bold px-3 py-1.5 rounded-xl" style={{ background: '#dcfce7', color: '#15803d', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        <i className="ri-checkbox-circle-line text-sm"></i>
                        ركبت
                      </span>
                    )}
                    {s === 'absent' && (
                      <span className="flex items-center gap-1 text-xs font-bold px-3 py-1.5 rounded-xl" style={{ background: '#fef2f2', color: '#dc2626', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        <i className="ri-close-circle-line text-sm"></i>
                        غائبة
                      </span>
                    )}
                  </div>
                </div>
              );
            })}
          </div>

          <div className="flex-shrink-0 px-5 py-4" style={{ borderTop: '1px solid #E0E7FF' }}>
            {pendingCount > 0 && (
              <p className="text-xs text-center text-amber-600 mb-2 font-semibold" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                ⚠️ لا يزال {pendingCount} طالبة لم يُحدد وضعها
              </p>
            )}
            <button
              onClick={handleConfirm}
              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', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
            >
              <i className="ri-check-double-line text-white"></i>
              تأكيد وإغلاق المحطة
            </button>
          </div>
        </div>
      </div>

      {showScanner && (
        <GlobalQRScanner
          passengers={passengers}
          statuses={statuses}
          onBoard={handleBoard}
          onClose={() => setShowScanner(false)}
        />
      )}
    </>
  );
}
