import React, { useEffect, useState } from 'react';
import { X, Calendar, Users, Navigation, Trash2, Loader2, Compass, Play } from 'lucide-react';
import { useTourStore } from '../../store/useTourStore';
import { useNotification } from '@/hooks/useNotification';
import { useConfirm } from '@/hooks/useConfirm';

interface MyToursModalProps {
  isOpen: boolean;
  onClose: () => void;
  user: any;
  onViewTour: (tourId: string) => void;
  onOpenNavigation?: (payload: any) => void;
}

export const MyToursModal: React.FC<MyToursModalProps> = ({
  isOpen,
  onClose,
  user,
  onViewTour,
  onOpenNavigation,
}) => {
  const notify = useNotification();
  const confirm = useConfirm();

  const publicTours = useTourStore(state => state.publicTours);
  const fetchPublicTours = useTourStore(state => state.fetchPublicTours);
  const deleteTour = useTourStore(state => state.deleteTour);

  const [isLoading, setIsLoading] = useState(false);
  const [isDeletingId, setIsDeletingId] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'ongoing' | 'upcoming' | 'past'>('ongoing');

  useEffect(() => {
    if (isOpen && user) {
      const loadTours = async () => {
        setIsLoading(true);
        try {
          await fetchPublicTours();
        } catch (e) {
          console.error(e);
        } finally {
          setIsLoading(false);
        }
      };
      loadTours();
    }
  }, [isOpen, fetchPublicTours, user]);

  if (!isOpen || !user) return null;

  // Filter tours where user is participant
  const myTours = publicTours.filter(tour =>
    tour.participants?.some((p: any) => p.userId === user?.id)
  );

  const now = new Date();

  // Classify tours
  const ongoingTours = myTours.filter(tour => {
    if (!tour.startDate || !tour.endDate) return false;
    const start = new Date(tour.startDate);
    const end = new Date(tour.endDate);
    return start <= now && end >= now;
  });

  const upcomingTours = myTours.filter(tour => {
    if (!tour.startDate) return true;
    const start = new Date(tour.startDate);
    return start > now;
  });

  const pastTours = myTours.filter(tour => {
    if (!tour.endDate) return false;
    const end = new Date(tour.endDate);
    return end < now;
  });

  const getActiveList = () => {
    switch (activeTab) {
      case 'ongoing': return ongoingTours;
      case 'upcoming': return upcomingTours;
      case 'past': return pastTours;
    }
  };

  const handleDelete = async (tourId: string, tourTitle: string) => {
    const ok = await confirm({
      title: 'Xóa chuyến đi?',
      message: `Bạn có chắc chắn muốn xóa chuyến đi "${tourTitle}" không? Hành động này không thể hoàn tác.`,
    });
    if (!ok) return;

    setIsDeletingId(tourId);
    try {
      await deleteTour(tourId);
      notify({
        title: 'Thành công',
        message: 'Đã xóa chuyến đi thành công.',
        type: 'success',
      });
    } catch (err: any) {
      notify({
        title: 'Lỗi',
        message: err.message || 'Xóa chuyến đi thất bại.',
        type: 'error',
      });
    } finally {
      setIsDeletingId(null);
    }
  };

  const handleStartNavigation = (tour: any) => {
    if (!onOpenNavigation) {
      notify({
        title: 'Lưu ý',
        message: 'Tính năng dẫn đường chỉ khả dụng trong chế độ bản đồ.',
        type: 'info',
      });
      return;
    }

    const firstLeg = tour.legs?.[0];
    const origin = firstLeg?.locations?.[0] || { lat: 10.7769, lng: 106.7009 };
    const destination = firstLeg?.locations?.[firstLeg?.locations?.length - 1] || { lat: 10.8231, lng: 106.6297, name: 'Điểm kết thúc' };

    onOpenNavigation({
      tourId: tour.id,
      origin: { lat: Number(origin.latitude || origin.lat), lng: Number(origin.longitude || origin.lng) },
      destination: {
        lat: Number(destination.latitude || destination.lat),
        lng: Number(destination.longitude || destination.lng),
        name: destination.name || 'Điểm kết thúc'
      },
      tourTitle: tour.title,
    });
    onClose();
  };

  // Calculate ongoing timeline progress percentage
  const getProgressPercent = (tour: any) => {
    if (!tour.startDate || !tour.endDate) return 0;
    const start = new Date(tour.startDate).getTime();
    const end = new Date(tour.endDate).getTime();
    const current = now.getTime();
    if (current >= end) return 100;
    if (current <= start) return 0;
    return Math.round(((current - start) / (end - start)) * 100);
  };

  const currentList = getActiveList();

  return (
    <div className="fixed inset-0 z-[1000000] bg-black/70 backdrop-blur-sm flex items-end sm:items-center justify-center p-0 sm:p-4 pointer-events-auto">
      <div className="bg-slate-900 w-full sm:max-w-2xl h-[92vh] sm:h-[80vh] rounded-t-3xl sm:rounded-2xl flex flex-col overflow-hidden text-slate-200 text-xs border border-slate-800/80 shadow-2xl animate-in slide-in-from-bottom sm:zoom-in-95 duration-300">

        {/* Header */}
        <div className="px-5 py-4 border-b border-slate-800/60 flex justify-between items-center shrink-0">
          <span className="font-bold text-sm text-white flex items-center gap-2">
            <Compass className="w-5 h-5 text-indigo-400" /> Hành trình của tôi
          </span>
          <button
            onClick={onClose}
            className="p-1.5 bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white rounded-lg transition-colors cursor-pointer"
          >
            <X className="w-4 h-4" />
          </button>
        </div>

        {/* Tab Selection Header */}
        <div className="bg-slate-950/40 p-2.5 border-b border-slate-850 flex gap-2 shrink-0">
          {[
            { id: 'ongoing', label: 'Đang thực hiện' },
            { id: 'upcoming', label: 'Sắp khởi hành' },
            { id: 'past', label: 'Đã hoàn thành' }
          ].map((tab) => {
            const isActive = activeTab === tab.id;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                className={`flex-1 py-2 rounded-xl text-center font-bold transition-all cursor-pointer ${isActive
                    ? 'bg-indigo-650 text-white shadow-md'
                    : 'bg-slate-900/40 hover:bg-slate-850 text-slate-400'
                  }`}
              >
                {tab.label}
              </button>
            );
          })}
        </div>

        {/* Content body */}
        <div className="flex-1 overflow-y-auto p-5">
          {isLoading ? (
            <div className="h-full flex items-center justify-center flex-col gap-2 py-20">
              <Loader2 className="w-8 h-8 text-indigo-400 animate-spin" />
              <span className="text-slate-400 font-medium">Đang tải danh sách chuyến đi...</span>
            </div>
          ) : currentList.length === 0 ? (
            <div className="h-full flex flex-col items-center justify-center text-center py-20 px-6 gap-3">
              <div className="w-16 h-16 bg-slate-850 rounded-full flex items-center justify-center border border-slate-800">
                <Compass className="w-8 h-8 text-slate-500" />
              </div>
              <div>
                <div className="font-bold text-white text-sm">Chưa có hành trình nào</div>
                <p className="text-slate-500 mt-1 max-w-xs mx-auto">Bạn không có chuyến đi nào trong mục này.</p>
              </div>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {currentList.map((tour) => {
                const isOwner = tour.participants?.some(
                  (p: any) => p.userId === user?.id && p.role === 'OWNER'
                );
                const startDateStr = tour.startDate ? new Date(tour.startDate).toLocaleDateString('vi-VN') : '';
                const endDateStr = tour.endDate ? new Date(tour.endDate).toLocaleDateString('vi-VN') : '';
                const progress = getProgressPercent(tour);

                // Fallback tour banner photo
                const tourBanner = tour.coverImage || 'https://images.unsplash.com/photo-1488646953014-85cb44e25828?w=500';

                return (
                  <div
                    key={tour.id}
                    className="bg-slate-950/40 border border-slate-850 hover:border-slate-750 rounded-2xl overflow-hidden flex flex-col justify-between transition-all"
                  >
                    {/* Banner cover */}
                    <div className="relative h-28 w-full overflow-hidden">
                      <img src={tourBanner} alt="Cover Banner" className="w-full h-full object-cover" />
                      <div className="absolute inset-0 bg-gradient-to-t from-slate-950 to-transparent opacity-90" />

                      <div className="absolute bottom-3 left-3 right-3 min-w-0">
                        <h4 className="font-bold text-white text-xs truncate drop-shadow-md">{tour.title}</h4>
                        <p className="text-[10px] text-slate-300 font-medium mt-0.5">{startDateStr} - {endDateStr}</p>
                      </div>
                    </div>

                    {/* Progress details */}
                    <div className="p-3.5 space-y-3 flex-1 flex flex-col justify-between">
                      {activeTab === 'ongoing' && (
                        <div className="space-y-1">
                          <div className="flex justify-between items-center text-[10px] text-slate-400 font-bold">
                            <span>Tiến độ hành trình</span>
                            <span className="text-indigo-400">{progress}%</span>
                          </div>
                          <div className="w-full bg-slate-800 h-1.5 rounded-full overflow-hidden">
                            <div className="bg-indigo-500 h-full rounded-full transition-all" style={{ width: `${progress}%` }} />
                          </div>
                        </div>
                      )}

                      <div className="flex items-center gap-3 text-[10px] text-slate-400 font-semibold">
                        <span className="flex items-center gap-1.5">
                          <Users className="w-3.5 h-3.5 text-slate-500" />
                          {tour.participants?.length || 0} thành viên
                        </span>
                        <span className="flex items-center gap-1.5">
                          <Navigation className="w-3.5 h-3.5 text-slate-500" />
                          {tour.legs?.length || 0} chặng đi
                        </span>
                      </div>

                      <div className="flex justify-end items-center gap-2 border-t border-slate-850/60 pt-3 mt-1">
                        {isOwner && (
                          <button
                            onClick={() => handleDelete(tour.id, tour.title)}
                            disabled={isDeletingId === tour.id}
                            className="p-2 text-rose-400 hover:bg-rose-500/10 rounded-xl transition-all cursor-pointer disabled:opacity-50"
                            title="Xóa chuyến đi"
                          >
                            {isDeletingId === tour.id ? (
                              <Loader2 className="w-3.5 h-3.5 animate-spin" />
                            ) : (
                              <Trash2 className="w-3.5 h-3.5" />
                            )}
                          </button>
                        )}

                        <button
                          onClick={() => handleStartNavigation(tour)}
                          className="flex items-center gap-1.5 px-3 py-1.5 bg-slate-800 hover:bg-slate-700 font-bold text-indigo-300 rounded-xl transition-all active:scale-95 cursor-pointer"
                          title="Bắt đầu dẫn đường"
                        >
                          <Play className="w-3 h-3 text-indigo-400 fill-indigo-400" /> Dẫn đường
                        </button>

                        <button
                          onClick={() => {
                            onClose();
                            onViewTour(tour.id);
                          }}
                          className="flex items-center gap-1.5 px-3.5 py-1.5 bg-indigo-650 hover:bg-indigo-600 font-bold text-white rounded-xl transition-all active:scale-95 cursor-pointer shadow-md shadow-indigo-900/10"
                        >
                          Hành trình Tour
                        </button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

      </div>
    </div>
  );
};
