import React, { useEffect, useState } from 'react';
import { X, Calendar, Users, Navigation, Trash2, Loader2, Compass } 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;
}

export const MyToursModal: React.FC<MyToursModalProps> = ({
  isOpen,
  onClose,
  user,
  onViewTour,
}) => {
  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);

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

  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 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);
    }
  };

  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-xl 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>

        {/* 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>
          ) : myTours.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 chưa tham gia chuyến đi nào. Hãy nhấp Tạo Tour mới để bắt đầu hành trình của riêng mình!</p>
              </div>
            </div>
          ) : (
            <div className="space-y-3.5">
              {myTours.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') : '';

                return (
                  <div 
                    key={tour.id} 
                    className="p-4 bg-slate-950/40 border border-slate-850 hover:border-slate-750 rounded-2xl flex flex-col gap-3 transition-all"
                  >
                    <div className="flex justify-between items-start gap-4">
                      <div className="min-w-0">
                        <h4 className="font-bold text-white text-sm truncate">{tour.title}</h4>
                        <div className="flex items-center gap-4 text-[10px] text-slate-400 mt-1 font-semibold">
                          <span className="flex items-center gap-1">
                            <Calendar className="w-3.5 h-3.5 text-slate-500 shrink-0" />
                            {startDateStr} - {endDateStr}
                          </span>
                          <span className="flex items-center gap-1">
                            <Users className="w-3.5 h-3.5 text-slate-500 shrink-0" />
                            {tour.participants?.length || 0} thành viên
                          </span>
                        </div>
                      </div>
                    </div>

                    <div className="flex justify-end items-center gap-2 border-t border-slate-850 pt-3">
                      {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 shrink-0 disabled:opacity-50"
                          title="Xóa chuyến đi"
                        >
                          {isDeletingId === tour.id ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : (
                            <Trash2 className="w-4 h-4" />
                          )}
                        </button>
                      )}

                      <button
                        onClick={() => {
                          onClose();
                          onViewTour(tour.id);
                        }}
                        className="flex items-center gap-1.5 px-4 py-2 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"
                      >
                        <Navigation className="w-3.5 h-3.5" /> Xem hành trình
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

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