// MyTripsPage.js
import React, { useState, useEffect } from 'react';
import { SearchIcon, ChevronDownIcon, MapPinIcon, ClockIcon, PlaneIcon, UserIcon, ScaleIcon, CalendarIcon } from '../Icons';
import { authFetch } from '../../App';
import ConfirmDeleteModal from "../ConfirmDeleteModal";
import { API_BASE_URL } from '@/src/config.js';
interface TripRequest {
    id: string;
    type: 'trip' | 'companion';
    title: string;
    requestDate: string;
    status: 'active' | 'pending' | 'completed';
    origin: string;
    destination: string;
    departureDate: string;
    capacity?: number;
    created_at?: string;
    origin_country?: string;
    origin_city?: string;
    destination_country?: string;
    destination_city?: string;
    vehicle_type?: string;
    vehicle_types?: string[];
    description?: string;
    show_phone?: boolean;
}

interface MyTripsPageProps {
    onNavigate: (page: string, payload?: any, options?: { isOwnerView?: boolean }) => void;
    showSuccess: (message: string) => void;
    showError: (message: string) => void;
}

const MyTripsPage: React.FC<MyTripsPageProps> = ({ onNavigate, showSuccess, showError }) => {
    const [searchQuery, setSearchQuery] = useState('');
    const [statusFilter, setStatusFilter] = useState('all');
    const [typeFilter, setTypeFilter] = useState('all');
    const [tripRequests, setTripRequests] = useState<TripRequest[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [deletingId, setDeletingId] = useState<string | null>(null);

    // اضافه کردن state برای مدال
    const [deleteModal, setDeleteModal] = useState<{ open: boolean; item: TripRequest | null }>({
        open: false,
        item: null
    });

    // تابع برای دریافت سفرهای کاربر از API
    const fetchUserTrips = async () => {
        try {
            setLoading(true);
            setError(null);

            // دریافت سفرهای کاربر
            const tripsResponse = await authFetch(`${API_BASE_URL}/trips/my-trips`);

            // دریافت همسفرهای کاربر
            const companionsResponse = await authFetch(`${API_BASE_URL}/trips/my-companions`);

            if (!tripsResponse.ok || !companionsResponse.ok) {
                throw new Error('خطا در دریافت اطلاعات');
            }

            const tripsData = await tripsResponse.json();
            const companionsData = await companionsResponse.json();

            // تبدیل داده‌های API به فرمت مورد نیاز کامپوننت
            const formattedTrips: TripRequest[] = tripsData.data?.map((trip: any) => ({
                id: trip.id.toString(),
                type: 'trip',
                title: `سفر از ${trip.origin_city} به ${trip.destination_city}`,
                requestDate: formatDate(trip.created_at),
                status: mapStatus(trip.status),
                origin: `${trip.origin_city}, ${trip.origin_country}`,
                destination: `${trip.destination_city}, ${trip.destination_country}`,
                departureDate: trip.departure_date,
                capacity: trip.capacity,
                created_at: trip.created_at,
                origin_country: trip.origin_country,
                origin_city: trip.origin_city,
                destination_country: trip.destination_country,
                destination_city: trip.destination_city,
                vehicle_type: trip.vehicle_type,
                description: trip.description,
                show_phone: trip.show_phone
            })) || [];

            const formattedCompanions: TripRequest[] = companionsData.data?.map((companion: any) => ({
                id: companion.id.toString(),
                type: 'companion',
                title: `همسفر برای مسیر ${companion.origin_city} به ${companion.destination_city}`,
                requestDate: formatDate(companion.created_at),
                status: mapStatus(companion.status),
                origin: `${companion.origin_city}, ${companion.origin_country}`,
                destination: `${companion.destination_city}, ${companion.destination_country}`,
                departureDate: companion.available_from,
                capacity: companion.capacity,
                created_at: companion.created_at,
                origin_country: companion.origin_country,
                origin_city: companion.origin_city,
                destination_country: companion.destination_country,
                destination_city: companion.destination_city,
                vehicle_types: companion.vehicle_types,
                description: companion.description,
                show_phone: companion.show_phone
            })) || [];

            // ترکیب سفرها و همسفرها
            const allRequests = [...formattedTrips, ...formattedCompanions];
            setTripRequests(allRequests);

        } catch (err: any) {
            setError(err.message || 'خطا در دریافت اطلاعات');
            console.error('Error fetching user trips:', err);
        } finally {
            setLoading(false);
        }
    };

    // تابع برای تبدیل وضعیت
    const mapStatus = (status: string): 'active' | 'pending' | 'completed' => {
        switch (status) {
            case 'active': return 'active';
            case 'completed': return 'completed';
            case 'cancelled': return 'completed';
            case 'inactive': return 'completed';
            default: return 'pending';
        }
    };

    // تابع برای فرمت تاریخ
    const formatDate = (dateString: string): string => {
        if (!dateString) return 'تاریخ نامعلوم';

        const date = new Date(dateString);
        const now = new Date();
        const diffMs = now.getTime() - date.getTime();
        const diffMins = Math.floor(diffMs / (1000 * 60));
        const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

        if (diffMins < 60) {
            return `${diffMins} دقیقه پیش`;
        } else if (diffHours < 24) {
            return `${diffHours} ساعت پیش`;
        } else if (diffDays < 7) {
            return `${diffDays} روز پیش`;
        } else {
            return new Date(dateString).toLocaleDateString('fa-IR');
        }
    };

    // فیلتر کردن ریکوئست‌ها
    const filteredRequests = tripRequests.filter(request => {
        const lowercasedQuery = searchQuery.toLowerCase();
        const matchesSearch = request.title.toLowerCase().includes(lowercasedQuery) ||
            request.origin.toLowerCase().includes(lowercasedQuery) ||
            request.destination.toLowerCase().includes(lowercasedQuery);

        const matchesStatus = statusFilter === 'all' || request.status === statusFilter;
        const matchesType = typeFilter === 'all' || request.type === typeFilter;

        return matchesSearch && matchesStatus && matchesType;
    });

    // دریافت داده‌ها هنگام لود کامپوننت
    useEffect(() => {
        fetchUserTrips();
    }, []);

    // تابع باز کردن مدال حذف
    const handleDeleteClick = (item: TripRequest) => {
        setDeleteModal({ open: true, item });
    };

    // تابع تایید حذف
    const handleConfirmDelete = async () => {
        if (!deleteModal.item) return;

        const itemToDelete = deleteModal.item;
        setDeletingId(itemToDelete.id);
        setDeleteModal({ open: false, item: null });

        try {
            const endpoint = itemToDelete.type === 'trip' ? 'trip' : 'companion';
            const response = await authFetch(`${API_BASE_URL}/trips/${endpoint}/${itemToDelete.id}`, {
                method: 'DELETE',
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || 'خطا در حذف');
            }

            showSuccess(itemToDelete.type === 'trip' ? 'سفر با موفقیت حذف شد' : 'همسفری با موفقیت حذف شد');
            // به‌روزرسانی لیست
            setTripRequests(prev => prev.filter(req => req.id !== itemToDelete.id));

        } catch (err: any) {
            showError(err.message || 'خطا در حذف آیتم');
        } finally {
            setDeletingId(null);
        }
    };

    // تابع لغو حذف
    const handleCancelDelete = () => {
        setDeleteModal({ open: false, item: null });
    };

    if (loading) {
        return (
            <div className="flex flex-col space-y-8">
                <div>
                    <h1 className="text-3xl font-bold text-gray-800 dark:text-white">لیست سفرهای من</h1>
                    <p className="text-gray-500 dark:text-gray-400 mt-1">در حال دریافت اطلاعات...</p>
                </div>
                <div className="flex justify-center items-center py-12">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-custom-purple"></div>
                </div>
            </div>
        );
    }

    if (error) {
        return (
            <div className="flex flex-col space-y-8">
                <div>
                    <h1 className="text-3xl font-bold text-gray-800 dark:text-white">لیست سفرهای من</h1>
                    <p className="text-gray-500 dark:text-gray-400 mt-1">خطا در دریافت اطلاعات</p>
                </div>
                <div className="text-center py-12 bg-custom-light-card dark:bg-custom-dark-blue-light rounded-2xl">
                    <div className="text-red-500 mb-4 text-4xl">⚠️</div>
                    <h3 className="text-xl font-semibold text-red-600 dark:text-red-400 mb-2">خطا در بارگذاری</h3>
                    <p className="text-red-500 dark:text-red-300 mb-4">{error}</p>
                    <button
                        onClick={fetchUserTrips}
                        className="bg-custom-purple hover:bg-custom-light-purple text-white px-6 py-2 rounded-lg transition-colors"
                    >
                        تلاش مجدد
                    </button>
                </div>
            </div>
        );
    }

    return (
        <div className="flex flex-col space-y-8">
            <div>
                <h1 className="text-3xl font-bold text-gray-800 dark:text-white">لیست سفرهای من</h1>
                <p className="text-gray-500 dark:text-gray-400 mt-1">سفرها و اعلام آمادگی‌های همسفری خود را مدیریت کنید.</p>
            </div>

            {/* آمار کلی */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-4 rounded-2xl shadow-sm">
                    <div className="flex items-center justify-between">
                        <div>
                            <p className="text-sm text-gray-500 dark:text-gray-400">کل سفرها</p>
                            <p className="text-2xl font-bold text-gray-800 dark:text-white">
                                {tripRequests.filter(req => req.type === 'trip').length}
                            </p>
                        </div>
                        <PlaneIcon className="w-8 h-8 text-custom-orange" />
                    </div>
                </div>
                <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-4 rounded-2xl shadow-sm">
                    <div className="flex items-center justify-between">
                        <div>
                            <p className="text-sm text-gray-500 dark:text-gray-400">کل همسفرها</p>
                            <p className="text-2xl font-bold text-gray-800 dark:text-white">
                                {tripRequests.filter(req => req.type === 'companion').length}
                            </p>
                        </div>
                        <UserIcon className="w-8 h-8 text-custom-cyan" />
                    </div>
                </div>
                <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-4 rounded-2xl shadow-sm">
                    <div className="flex items-center justify-between">
                        <div>
                            <p className="text-sm text-gray-500 dark:text-gray-400">فعال</p>
                            <p className="text-2xl font-bold text-gray-800 dark:text-white">
                                {tripRequests.filter(req => req.status === 'active').length}
                            </p>
                        </div>
                        <div className="w-8 h-8 bg-green-500 rounded-full flex items-center justify-center">
                            <span className="text-white text-sm">✓</span>
                        </div>
                    </div>
                </div>
            </div>

            {/* فیلترها */}
            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                <div className="w-full grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div className="relative">
                        <input
                            type="text"
                            placeholder="جستجو در عنوان، مبدأ یا مقصد..."
                            className="w-full pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition"
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                        />
                        <SearchIcon className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                    </div>
                    <div className="relative">
                        <select
                            className="w-full appearance-none pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition"
                            value={statusFilter}
                            onChange={(e) => setStatusFilter(e.target.value)}
                        >
                            <option value="all">همه وضعیت‌ها</option>
                            <option value="active">فعال</option>
                            <option value="pending">در حال بررسی</option>
                            <option value="completed">انجام شده</option>
                        </select>
                        <ChevronDownIcon className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 pointer-events-none" />
                    </div>
                    <div className="relative">
                        <select
                            className="w-full appearance-none pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition"
                            value={typeFilter}
                            onChange={(e) => setTypeFilter(e.target.value)}
                        >
                            <option value="all">همه انواع</option>
                            <option value="trip">سفرهای من</option>
                            <option value="companion">همسفری‌های من</option>
                        </select>
                        <ChevronDownIcon className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 pointer-events-none" />
                    </div>
                </div>
            </div>

            {/* لیست ریکوئست‌ها */}
            <div className="space-y-6">
                {filteredRequests.length > 0 ? (
                    filteredRequests.map(request => (
                        <TripRequestCard
                            key={`${request.type}-${request.id}`}
                            request={request}
                            onNavigate={onNavigate}
                            onDelete={handleDeleteClick}
                            isDeleting={deletingId === request.id}
                        />
                    ))
                ) : (
                    <div className="text-center py-12 bg-custom-light-card dark:bg-custom-dark-blue-light rounded-2xl">
                        <PlaneIcon className="w-16 h-16 mx-auto text-gray-300 dark:text-gray-600" />
                        <h3 className="mt-4 text-xl font-semibold text-gray-800 dark:text-gray-200">سفری یافت نشد</h3>
                        <p className="mt-1 text-gray-500 dark:text-gray-400">
                            {tripRequests.length === 0
                                ? 'هنوز هیچ سفری ثبت نکرده‌اید.'
                                : 'هیچ سفری با این مشخصات یافت نشد.'
                            }
                        </p>
                        {tripRequests.length === 0 && (
                            <button
                                onClick={() => onNavigate('register-trip')}
                                className="mt-4 bg-custom-purple hover:bg-custom-light-purple text-white font-bold py-2 px-6 rounded-lg transition-colors duration-300"
                            >
                                ثبت اولین سفر
                            </button>
                        )}
                    </div>
                )}
            </div>

            {/* مدال تایید حذف */}
            <ConfirmDeleteModal
                open={deleteModal.open}
                title={deleteModal.item?.type === 'trip' ? 'حذف سفر' : 'حذف همسفری'}
                message={`آیا از حذف "${deleteModal.item?.title}" مطمئن هستید؟ این عملیات غیرقابل بازگشت است.`}
                onCancel={handleCancelDelete}
                onConfirm={handleConfirmDelete}
            />
        </div>
    );
};

interface TripRequestCardProps {
    request: TripRequest;
    onNavigate: (page: string, payload?: any, options?: { isOwnerView?: boolean }) => void;
    onDelete: (item: TripRequest) => void;
    isDeleting: boolean;
}

const TripRequestCard: React.FC<TripRequestCardProps> = ({ request, onNavigate, onDelete, isDeleting }) => {
    const { id, type, title, requestDate, status, origin, destination, departureDate, capacity } = request;

    const getStatusChip = () => {
        switch (status) {
            case 'active': return <span className="px-3 py-1 text-xs font-bold rounded-full bg-green-500/10 text-green-500">فعال</span>;
            case 'pending': return <span className="px-3 py-1 text-xs font-bold rounded-full bg-custom-orange/10 text-custom-orange">در حال بررسی</span>;
            case 'completed': return <span className="px-3 py-1 text-xs font-bold rounded-full bg-gray-500/10 text-gray-500 dark:bg-gray-400/10 dark:text-gray-400">انجام شده</span>;
        }
    };

    const isTrip = type === 'trip';

    return (
        <div className="flex flex-col md:flex-row md:items-center gap-6 bg-custom-light-card dark:bg-custom-dark-blue-light p-5 rounded-2xl shadow-sm border border-transparent hover:border-custom-purple/50 hover:shadow-lg transition-all duration-300">
            <div className="flex-shrink-0 w-full md:w-32 h-32 bg-custom-light-bg dark:bg-custom-dark-blue rounded-xl flex items-center justify-center">
                {isTrip ? <PlaneIcon className="w-16 h-16 text-custom-purple/50" /> : <UserIcon className="w-16 h-16 text-custom-purple/50" />}
            </div>

            <div className="flex flex-col flex-grow w-full">
                <div className="flex justify-between items-start mb-3">
                    <div>
                        <div className={`flex items-center gap-2 mb-1 ${isTrip ? 'text-custom-orange' : 'text-custom-cyan'}`}>
                            {isTrip ? <PlaneIcon className="w-5 h-5" /> : <UserIcon className="w-5 h-5" />}
                            <span className="text-sm font-semibold">{isTrip ? 'سفر' : 'همسفری'}</span>
                        </div>
                        <h3 className="text-lg font-bold text-gray-800 dark:text-white">{title}</h3>
                    </div>
                    <div className="flex-shrink-0">
                        {getStatusChip()}
                    </div>
                </div>

                <div className="flex-grow space-y-2 text-sm text-gray-600 dark:text-gray-300 border-t border-gray-200 dark:border-gray-700 pt-3">
                    <InfoRow icon={ClockIcon} label="تاریخ ثبت" value={requestDate} />
                    <InfoRow icon={MapPinIcon} label="مبدأ" value={origin} />
                    <InfoRow icon={MapPinIcon} label="مقصد" value={destination} />
                    <InfoRow icon={CalendarIcon} label="تاریخ حرکت" value={departureDate} />
                    {isTrip && capacity !== undefined && (
                        <InfoRow icon={ScaleIcon} label="ظرفیت" value={`${capacity} کیلوگرم`} />
                    )}
                </div>

                <div className="mt-4 flex items-center justify-end gap-3">
                    <button
                        onClick={() => onDelete(request)}
                        disabled={isDeleting}
                        className="flex items-center gap-2 bg-red-500 hover:bg-red-600 disabled:bg-gray-400 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-300 text-sm"
                    >
                        {isDeleting ? (
                            <>
                                <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                                <span>در حال حذف...</span>
                            </>
                        ) : (
                            <span>حذف</span>
                        )}
                    </button>
                    <button
                        onClick={() => onNavigate('trip-detail', { tripId: id, type: type }, { isOwnerView: true })}
                        className="bg-custom-purple hover:bg-custom-light-purple text-white font-bold py-2 px-6 rounded-lg transition-colors duration-300 text-sm"
                    >
                        مشاهده جزئیات
                    </button>
                </div>
            </div>
        </div>
    );
};

const InfoRow: React.FC<{ icon: React.FC<{ className?: string }>, label: string, value?: string, valueClassName?: string }> = ({ icon: Icon, label, value, valueClassName = 'text-gray-800 dark:text-gray-200' }) => (
    <div className="flex items-center justify-between">
        <div className="flex items-center text-gray-500 dark:text-gray-400">
            <Icon className="w-4 h-4 ml-2" />
            <span>{label}:</span>
        </div>
        <span className={`font-semibold ${valueClassName}`}>{value || '-'}</span>
    </div>
);

export default MyTripsPage;