"use client"

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

export interface Order {
    id: number;
    timestamp: string;
    buyerId: string;
    orderId: string;
    name: string;
    mobile: string;
    email: string;
    billingType: string;
    orderType: string;
    billingAddress: string;
    shippingAddress: string;
    invoiceAmount: string;
    totalAmtBeforeDiscount: string;
    uploadedImageLink: string;
    paymentTerms: string;
    paymentCollectionDate: string;
    orderTakenBy: string;
    whatsappSMS: string;
    piLink: string;
    piUrl: string;
    planned: string;
    actualDelay: string;
    fmsUserName: string;
    activeStage: number; // 0–6
    status?: 'Cancelled' | 'Hold' | 'Normal';
    editOrderLink?: string;
}

const API_URL = 'https://script.google.com/macros/s/AKfycbwaNGxqJU1MnCFCu6oTAF4Yd-Qh2gsl2LEZ_zdndqfzSctoPs7jG7MwZSgWfzPK4qIyGQ/exec';

/**
 * Helper to convert Google Sheets duration (ISO date string) to HH:MM:SS
 */
function formatDuration(isoString: string): string {
    if (!isoString || isoString === '—' || isoString === '') return '—';
    const date = new Date(isoString);
    if (isNaN(date.getTime())) return isoString;
    
    // Excel/Sheets base date is 1899-12-30
    const baseDate = new Date('1899-12-30T00:00:00.000Z');
    const diffMs = date.getTime() - baseDate.getTime();
    
    if (diffMs < 0) return '00:00:00';

    const totalSeconds = Math.floor(diffMs / 1000);
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;
    
    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}

/**
 * Helper to format date strings for display
 */
function formatDate(dateStr: string): string {
    if (!dateStr || dateStr === '—' || dateStr === '') return '—';
    try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return dateStr;
        
        const d = String(date.getDate()).padStart(2, '0');
        const m = String(date.getMonth() + 1).padStart(2, '0');
        const y = date.getFullYear();
        const h = String(date.getHours()).padStart(2, '0');
        const min = String(date.getMinutes()).padStart(2, '0');
        
        return `${d}/${m}/${y} ${h}:${min}`;
    } catch (e) {
        return dateStr;
    }
}

export function useNewOrderFMS() {
    const [orders, setOrders] = useState<Order[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    // Load from cache on mount
    useEffect(() => {
        const cached = localStorage.getItem('fms_orders_cache');
        if (cached) {
            try {
                const parsed = JSON.parse(cached);
                if (Array.isArray(parsed) && parsed.length > 0) {
                    setOrders(parsed);
                    setLoading(false); // We have some data to show
                }
            } catch (e) {
                console.error('Failed to parse cached orders');
            }
        }
    }, []);

    const fetchOrders = useCallback(async () => {
        // Only show full-screen loader if we have no data at all
        setLoading(orders.length === 0);
        setError(null);
        try {
            const response = await fetch(API_URL);
            if (!response.ok) throw new Error('Failed to fetch orders');
            const result = await response.json();
            
            if (!result.success || !Array.isArray(result.data)) {
                throw new Error('Invalid API response format');
            }

            const mappedOrders: Order[] = result.data.map((item: any) => {
                // Determine activeStage based on status or other fields
                // For now, let's map known statuses to stages if possible
                let activeStage = 0;
                const status = item.orderStatus?.toLowerCase() || '';
                
                if (status.includes('dispatch') || status.includes('ok to dispatch')) {
                    activeStage = 6;
                } else if (status.includes('qc')) {
                    activeStage = 4;
                } else if (status.includes('packing')) {
                    activeStage = 3;
                } else if (status.includes('payment')) {
                    activeStage = 2;
                } else if (status.includes('inventory')) {
                    activeStage = 1;
                }

                // Format currency robustly
                const parseAmt = (val) => {
                    if (typeof val === 'number') return val;
                    if (!val) return 0;
                    return parseFloat(String(val).replace(/[₹,]/g, '')) || 0;
                };

                const invAmt = parseAmt(item.invoiceAmount);
                const invoiceAmt = `₹${Math.round(invAmt).toLocaleString('en-IN')}`;

                const totAmt = parseAmt(item.totalAmountBeforeDiscount);
                const totalAmtBeforeDiscount = totAmt > 0 ? `₹${Math.round(totAmt).toLocaleString('en-IN')}` : '';

                return {
                    id: item.rowIndex,
                    timestamp: formatDate(item.timestamp),
                    buyerId: item.buyerId || '',
                    orderId: item.orderId || '',
                    name: item.clientName || 'Unknown',
                    mobile: String(item.mobile || ''),
                    email: item.email || '',
                    billingType: item.billingType || '',
                    orderType: item.orderType || '',
                    billingAddress: item.billingAddress || '',
                    shippingAddress: item.shippingAddress || '',
                    invoiceAmount: invoiceAmt,
                    totalAmtBeforeDiscount: totalAmtBeforeDiscount,
                    uploadedImageLink: item.uploadedImageLink || '',
                    paymentTerms: item.paymentTerms || '',
                    paymentCollectionDate: formatDate(item.paymentCollectionDate),
                    orderTakenBy: item.orderTakenBy || '',
                    whatsappSMS: item.whatsappSMS || 'Pending',
                    piLink: item.piNo || '',
                    piUrl: item.piUrl || '',
                    planned: formatDate(item.planned),
                    actualDelay: formatDuration(item.timeDelay),
                    fmsUserName: item.fmsUserName || '',
                    activeStage: activeStage,
                    status: (status.includes('cancel') || status.includes('cancelled')) ? 'Cancelled' : 
                            status.includes('hold') ? 'Hold' : 'Normal',
                    editOrderLink: item.editOrderLink || '',
                };
            });

            setOrders(mappedOrders);
            // Update cache
            localStorage.setItem('fms_orders_cache', JSON.stringify(mappedOrders));
            localStorage.setItem('fms_orders_last_fetch', new Date().toISOString());
        } catch (err: any) {
            console.error('Error fetching FMS orders:', err);
            setError(err.message);
        } finally {
            setLoading(false);
        }
    }, []);

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

    return { orders, loading, error, refresh: fetchOrders };
}
