import { useState, useEffect } from "react";
import Modal from "../../../components/Modals";
import IconBox from "../../../components/Icon/IconBox";
import Timeline from "../../../components/Timeline";
import api from '../../../api/axios';
import { toast } from 'react-toastify';

interface Props {
    open: boolean;
    onClose: () => void;
    onSave: (data: any) => Promise<void>;
    data: any;
}

interface HistoryItem {
    id: number;
    asset_id: string;
    changed_by: number;
    changed_by_name: string;
    action: string;
    field_name: string | null;
    old_value: string | null;
    new_value: string | null;
    reason: string | null;
    created_at: string;
    formatted_date: string;
    formatted_time: string;
    formatted_datetime: string;
}

interface AssetData {
    id: string;
    asset_name: string;
    category: string;
    status: number;
    status_text: string;
}

const MaintenanceLog = ({ open, onClose, data }: Props) => {
    const [history, setHistory] = useState<HistoryItem[]>([]);
    const [assetData, setAssetData] = useState<AssetData | null>(null);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        if (open && data?.id) {
            fetchMaintenanceHistory();
        }
    }, [open, data?.id]);

    const fetchMaintenanceHistory = async () => {
        setLoading(true);
        try {
            // Updated endpoint to match your route
            const response = await api.get(`/assets/maintenance-history/${data.id}`);

            if (response.data.status === 200) {
                // The history is inside response.data.data.history
                const historyData = response.data.data.history || [];
                setHistory(historyData);

                // Set asset data if available
                if (response.data.data.asset) {
                    setAssetData(response.data.data.asset);
                }
            }
        } catch (error) {
            console.error("Error fetching maintenance history:", error);
            toast.error("Failed to fetch maintenance history");
        } finally {
            setLoading(false);
        }
    };

    const getStatusColor = (action: string) => {
        const lowerAction = action?.toLowerCase() || '';
        if (lowerAction.includes('status') || lowerAction.includes('maintenance')) {
            if (lowerAction.includes('under maintenance')) return 'bg-blue-50 text-blue-500';
            if (lowerAction.includes('working')) return 'bg-green-50 text-green-500';
            if (lowerAction.includes('scrapped')) return 'bg-red-50 text-red-500';
        }
        return 'bg-gray-50 text-gray-500';
    };

    const formatActionDisplay = (item: HistoryItem) => {
        // Handle status changes
        if (item.field_name === 'status') {
            const statusColor = getStatusColor(item.new_value || item.action);
            return (
                <div className={`flex items-center gap-2 px-2 py-1 rounded ${statusColor}`}>
                    <label className="mb-0 text-sm">
                        {item.new_value || item.action}
                    </label>
                </div>
            );
        }

        // Handle field updates
        if (item.field_name) {
            return (
                <div className="flex items-center gap-2 bg-gray-50 px-2 py-1 rounded">
                    <label className="mb-0 text-sm text-gray-600">
                        {item.field_name}: {item.old_value || 'N/A'} → {item.new_value || 'N/A'}
                    </label>
                </div>
            );
        }

        // Default display
        return (
            <div className="flex items-center gap-2 bg-gray-50 px-2 py-1 rounded">
                <label className="mb-0 text-sm text-gray-600">{item.action}</label>
            </div>
        );
    };

    // Ensure history is an array before mapping
    const timelineData = Array.isArray(history) ? history.map((item) => ({
        date: item.formatted_date || (item.created_at ? new Date(item.created_at).toLocaleDateString('en-GB', { day: '2-digit', month: 'short' }) : 'N/A'),
        time: item.formatted_time || (item.created_at ? new Date(item.created_at).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' }) : 'N/A'),
        title: (
            <div className="flex items-center justify-between w-full flex-wrap gap-2">
                <div className="flex flex-col">
                    <label className="mb-0 font-medium">{item.changed_by_name || 'System'}</label>
                    <label className="text-gray-500 text-xs">{item.action}</label>
                    {item.reason && (
                        <label className="text-gray-400 text-xs mt-1">
                            Reason: {item.reason}
                        </label>
                    )}
                </div>
                {formatActionDisplay(item)}
            </div>
        )
    })) : [];

    // Use asset data from API or fallback to prop data
    const displayAsset = assetData || data;

    if (!displayAsset) return null;

    return (
        <Modal
            open={open}
            onClose={onClose}
            title="Maintenance Log"
            maxWidth="max-w-xl"
        >
            <div className="grid grid-cols-12 gap-4">
                <div className="col-span-12 flex gap-2 items-center">
                    <div className='p-4 rounded-xl bg-[#FCE7F3] text-primary'>
                        <IconBox />
                    </div>
                    <div className="flex flex-col">
                        <label className="font-semibold text-lg text-primary mb-0">
                            {displayAsset.asset_name}
                        </label>
                        <label className="text-sm text-gray-500 mb-0">
                            {displayAsset.category}
                        </label>
                        {displayAsset.status_text && (
                            <label className={`text-xs mt-1 px-2 py-0.5 rounded-full w-fit ${
                                displayAsset.status_text === 'Working' ? 'bg-green-100 text-green-600' :
                                displayAsset.status_text === 'UnderMaintenance' ? 'bg-blue-100 text-blue-600' :
                                displayAsset.status_text === 'Scrapped' ? 'bg-red-100 text-red-600' :
                                'bg-gray-100 text-gray-600'
                            }`}>
                                {displayAsset.status_text === 'UnderMaintenance' ? 'Under Maintenance' : displayAsset.status_text}
                            </label>
                        )}
                    </div>
                </div>

                <div className="col-span-12 border-b"></div>

                <div className="col-span-12 pb-5 max-h-[400px] overflow-y-auto">
                    {loading ? (
                        <div className="flex justify-center py-8">
                            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                        </div>
                    ) : timelineData.length === 0 ? (
                        <div className="text-center py-8 text-gray-500">
                            No maintenance history found
                        </div>
                    ) : (
                        <Timeline items={timelineData} />
                    )}
                </div>
            </div>
        </Modal>
    );
};

export default MaintenanceLog;
