import React, { useState, useEffect } from 'react';
import Sidebar from './components/Sidebar';
import Header from './components/Header';
import DashboardPage from './components/pages/DashboardPage';
import RegisterShipmentPage from './components/pages/RegisterShipmentPage';
import AcceptShipmentPage from './components/pages/AcceptShipmentPage';
import RegisterTripPage from './components/pages/RegisterTripPage';
import AcceptCompanionPage from './components/pages/AcceptCompanionPage';
import NewTicketPage from './components/pages/NewTicketPage';
import RegisterOnlinePurchasePage from './components/pages/RegisterOnlinePurchasePage';
import AcceptOnlinePurchasePage from './components/pages/AcceptOnlinePurchasePage';
import MyPurchaseRequestsPage from './components/pages/MyPurchaseRequestsPage';
import MyShipmentRequestsPage from './components/pages/MyShipmentRequestsPage';
import MyTripsPage from './components/pages/MyTripsPage';
import MessagesPage from './components/pages/MessagesPage';
import TicketListPage from './components/pages/TicketsPage';
import TicketDetailPage from './components/pages/TicketDetailPage';
import AccountPage from './components/pages/AccountPage';
import LoginPage from './components/auth/LoginPage';
import VerificationPage from './components/auth/VerificationPage';
import ShipmentDetailPage from './components/pages/ShipmentDetailPage';
import TripDetailPage from './components/pages/TripDetailPage';
import PurchaseDetailPage from './components/pages/PurchaseDetailPage';
import { API_BASE_URL } from '@/src/config.js';
const App: React.FC = () => {
    const [isSidebarOpen, setSidebarOpen] = useState(false);
    const [theme, setTheme] = useState('dark');
    const [currentPage, setCurrentPage] = useState('dashboard');
    const [selectedTicketId, setSelectedTicketId] = useState<string | null>(null);
    const [selectedShipmentId, setSelectedShipmentId] = useState<string | null>(null);
    const [selectedTripId, setSelectedTripId] = useState<string | null>(null);
    
    // ✅ ✨ اضافه شده: state برای نوع سفر
    const [selectedTripType, setSelectedTripType] = useState<'trip' | 'companion' | null>(null);

    const [selectedPurchaseRequestId, setSelectedPurchaseRequestId] = useState<string | null>(null);
    const [selectedPurchaseShopperId, setSelectedPurchaseShopperId] = useState<string | null>(null);
    const [isOwnerViewingDetail, setIsOwnerViewingDetail] = useState(false);

    const [isAuthenticated, setIsAuthenticated] = useState(false);
    const [loginStep, setLoginStep] = useState<'phone' | 'code'>('phone');
    const [message, setMessage] = useState<{ text: string; type: 'error' | 'success' } | null>(null);

    const showError = (text: string) => {
        setMessage({ text, type: 'error' });
        setTimeout(() => setMessage(null), 5000);
    };

    const showSuccess = (text: string) => {
        setMessage({ text, type: 'success' });
        setTimeout(() => setMessage(null), 5000);
    };

    const checkAuthStatus = async () => {
        const token = localStorage.getItem('auth_token');
        if (!token) {
            setIsAuthenticated(false);
            setLoginStep('phone');
            return;
        }

        try {
            const response = await fetch(`${API_BASE_URL}/auth/check`, {
                headers: {
                   
                    'X-Auth-Token': token,
                    'Content-Type': 'application/json',
                },
            });

            if (response.ok) {
                setIsAuthenticated(true);
            } else {
                throw new Error('توکن شما منقضی شده است.');
            }
        } catch (error) {
            localStorage.removeItem('auth_token');
            localStorage.removeItem('auth_phone');
            setIsAuthenticated(false);
            setLoginStep('phone');
            showError('لطفاً دوباره وارد شوید.');
        }
    };

    useEffect(() => {
        checkAuthStatus();
    }, []);

    useEffect(() => {
        const savedTheme = localStorage.getItem('theme');
        if (savedTheme && (savedTheme === 'light' || savedTheme === 'dark')) {
            setTheme(savedTheme);
        } else {
            localStorage.setItem('theme', 'dark');
        }
    }, []);

    useEffect(() => {
        if (theme === 'dark') {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
        localStorage.setItem('theme', theme);
    }, [theme]);

    const toggleTheme = () => {
        setTheme(prevTheme => (prevTheme === 'dark' ? 'light' : 'dark'));
    };

    const toggleSidebar = () => {
        setSidebarOpen(!isSidebarOpen);
    };

    const handleNavigation = async (page: string, payload?: any, options?: { isOwnerView?: boolean }) => {
        // ✅ ریست تمام stateهای مربوط به جزئیات
        setSelectedTicketId(null);
        setSelectedShipmentId(null);
        setSelectedTripId(null);
        setSelectedTripType(null); // ✅ ریست نوع
        setSelectedPurchaseRequestId(null);
        setSelectedPurchaseShopperId(null);
        setIsOwnerViewingDetail(options?.isOwnerView ?? false);

        // ✅ استخراج صحیح بر اساس نوع صفحه
        if (page === 'ticket-detail' && payload) {
            setSelectedTicketId(payload);
        } else if (page === 'shipment-detail' && payload) {
            setSelectedShipmentId(payload);
        } else if (page === 'trip-detail' && payload && typeof payload === 'object') {
            setSelectedTripId(payload.tripId);
            setSelectedTripType(payload.type || 'trip'); // ✅ ذخیره type
        } else if (page === 'purchase-request-detail' && payload) {
            setSelectedPurchaseRequestId(payload);
        } else if (page === 'purchase-shopper-detail' && payload) {
            setSelectedPurchaseShopperId(payload);
        }

        if (page === 'logout') {
            localStorage.removeItem('auth_token');
            localStorage.removeItem('auth_phone');
            setIsAuthenticated(false);
            setLoginStep('phone');
            setCurrentPage('dashboard');
            return;
        }

        await checkAuthStatus();

        if (isAuthenticated) {
            setCurrentPage(page);
            setSidebarOpen(false);
        }
    };

    const renderContent = () => {
        switch (currentPage) {
            case 'dashboard':
                return <DashboardPage onNavigate={handleNavigation} />;
            case 'register-shipment':
                return <RegisterShipmentPage showError={showError} showSuccess={showSuccess} />;
            case 'accept-shipment':
                return <AcceptShipmentPage onNavigate={handleNavigation} />;
            case 'my-shipment-requests':
                return <MyShipmentRequestsPage showError={showError} showSuccess={showSuccess} onNavigate={handleNavigation} />;
            case 'register-trip':
                return <RegisterTripPage showError={showError} showSuccess={showSuccess} />;
            case 'accept-companion':
                return <AcceptCompanionPage onNavigate={handleNavigation} />;
            case 'my-trips':
                return <MyTripsPage showError={showError} showSuccess={showSuccess} onNavigate={handleNavigation} />;
            case 'new-ticket':
                return <NewTicketPage onNavigate={handleNavigation} />;
            case 'register-online-purchase':
                return <RegisterOnlinePurchasePage showError={showError} showSuccess={showSuccess} />;
            case 'accept-online-purchase':
                return <AcceptOnlinePurchasePage onNavigate={handleNavigation} />;
            case 'my-purchase-requests':
                return <MyPurchaseRequestsPage showError={showError} showSuccess={showSuccess} onNavigate={handleNavigation} />;
            case 'messages':
                return <MessagesPage />;
            case 'tickets':
                return <TicketListPage onNavigate={handleNavigation} />;
            case 'ticket-detail':
                return <TicketDetailPage ticketId={selectedTicketId} onNavigate={handleNavigation} />;
            case 'shipment-detail':
                return <ShipmentDetailPage shipmentId={selectedShipmentId} onNavigate={handleNavigation} isOwnerView={isOwnerViewingDetail} />;
            case 'trip-detail':
                return (
                    <TripDetailPage
                        tripId={selectedTripId}
                        type={selectedTripType} // ✅ ارسال type
                        onNavigate={handleNavigation}
                        isOwnerView={isOwnerViewingDetail}
                    />
                );
            case 'purchase-request-detail':
                return (
                    <PurchaseDetailPage
                        purchaseId={selectedPurchaseRequestId}
                        onNavigate={handleNavigation}
                        isOwnerView={isOwnerViewingDetail}
                        type="request"
                    />
                );
            case 'purchase-shopper-detail':
                return (
                    <PurchaseDetailPage
                        purchaseId={selectedPurchaseShopperId}
                        onNavigate={handleNavigation}
                        isOwnerView={isOwnerViewingDetail}
                        type="shopper"
                    />
                );
            case 'account':
                return <AccountPage />;
            default:
                return <DashboardPage onNavigate={handleNavigation} />;
        }
    };

    const handlePhoneSubmit = async (phone: string) => {
        try {
            const response = await fetch(`${API_BASE_URL}/auth/request-otp`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ phone })
            });

            const data = await response.json();

            if (response.ok) {
                setLoginStep('code');
                localStorage.setItem('auth_phone', phone);
            } else {
                showError(data.error || 'خطا در ارسال کد');
            }
        } catch (err) {
            showError('اتصال به سرور برقرار نشد');
        }
    };

    const handleCodeSubmit = async (code: string) => {
        const phone = localStorage.getItem('auth_phone');
        if (!phone) return;

        try {
            const response = await fetch(`${API_BASE_URL}/auth/verify-otp`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ phone, otp: code })
            });

            const data = await response.json();

            if (response.ok) {
                localStorage.setItem('auth_token', data.token);
                setIsAuthenticated(true);
            } else {
                showError(data.error || 'کد نامعتبر است');
            }
        } catch (err) {
            showError('اتصال به سرور برقرار نشد');
        }
    };

    const handleResendCode = async () => {
        const phone = localStorage.getItem('auth_phone');
        if (!phone) return;

        try {
            const response = await fetch(`${API_BASE_URL}/auth/request-otp`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ phone })
            });

            if (response.ok) {
                showSuccess('کد جدید ارسال شد!');
            } else {
                const data = await response.json();
                showError(data.message || 'خطا در ارسال مجدد');
            }
        } catch (err) {
            showError('اتصال به سرور برقرار نشد');
        }
    };

    if (!isAuthenticated) {
        return (
            <>
                {message && (
                    <div
                        className={`fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg text-white font-medium z-50 ${
                            message.type === 'success' ? 'bg-green-500' : 'bg-red-500'
                        }`}
                    >
                        {message.text}
                    </div>
                )}

                {loginStep === 'phone' && (
                    <LoginPage onLogin={handlePhoneSubmit} theme={theme} toggleTheme={toggleTheme} />
                )}
                {loginStep === 'code' && (
                    <VerificationPage onVerify={handleCodeSubmit} onResend={handleResendCode} theme={theme} toggleTheme={toggleTheme} />
                )}
            </>
        );
    }

    const isMessagesPage = currentPage === 'messages';

    return (
        <div className="bg-custom-light-bg dark:bg-custom-dark-blue min-h-screen text-gray-800 dark:text-gray-200 font-sans flex relative">
            {message && (
                <div
                    className={`fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg text-white font-medium z-50 ${
                        message.type === 'success' ? 'bg-green-500' : 'bg-red-500'
                    }`}
                >
                    {message.text}
                </div>
            )}

            <Sidebar isOpen={isSidebarOpen} currentPage={currentPage} onNavigate={handleNavigation} />
            <div className="flex-1 flex flex-col overflow-x-hidden">
                <Header onMenuClick={toggleSidebar} theme={theme} toggleTheme={toggleTheme} onNavigate={handleNavigation} />
                <main className={`flex-1 p-4 sm:p-6 lg:p-8 ${isMessagesPage ? 'flex flex-col' : 'overflow-y-auto'}`}>
                    {renderContent()}
                </main>
            </div>
            {isSidebarOpen && (
                <div
                    onClick={() => setSidebarOpen(false)}
                    className="bg-black/50 fixed inset-0 z-30 lg:hidden"
                    aria-hidden="true"
                ></div>
            )}
        </div>
    );
};

export const authFetch = async (url: string, options: RequestInit = {}) => {
    const token = localStorage.getItem('auth_token');

    if (!token) {
        localStorage.removeItem('auth_token');
        localStorage.removeItem('auth_phone');
        window.location.reload();
        throw new Error('Not authenticated');
    }

    const response = await fetch(url, {
        ...options,
        headers: {
            'X-Auth-Token': token,  // ✅ تغییر داده شد
            'Content-Type': 'application/json',
            ...options.headers,
        },
    });

    if (response.status === 401) {
        localStorage.removeItem('auth_token');
        localStorage.removeItem('auth_phone');
        window.location.reload();
        throw new Error('Token expired or invalid');
    }

    if (!response.ok) {
        const data = await response.json().catch(() => ({}));
        throw new Error(data.error || 'خطا در انجام عملیات');
    }

    return response;
};


export default App;