import { useEffect, useState } from 'react';
import { format } from 'date-fns';
import { PlantLifecycleEvent, layoutApi } from '../../lib/layoutApi';
import { cn } from '../../lib/utils';
import {
    Move,
    Sprout,
    Trash2,
    FileText,
    CheckCircle,
    Scissors,
    ArrowRight
} from 'lucide-react';

interface PlantHistoryTimelineProps {
    plantId: string;
    className?: string;
}

export function PlantHistoryTimeline({ plantId, className }: PlantHistoryTimelineProps) {
    const [events, setEvents] = useState<PlantLifecycleEvent[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        async function fetchHistory() {
            setLoading(true);
            try {
                const data = await layoutApi.getPlantHistory(plantId);
                setEvents(data);
            } catch (error) {
                console.error('Failed to load plant history', error);
            } finally {
                setLoading(false);
            }
        }
        if (plantId) fetchHistory();
    }, [plantId]);

    if (loading) return <div className="text-center p-4 text-xs text-muted-foreground">Loading history...</div>;
    if (events.length === 0) return <div className="text-center p-4 text-xs text-muted-foreground">No history recorded</div>;

    return (
        <div className={cn("space-y-4", className)}>
            <div className="absolute left-3 top-2 bottom-2 w-px bg-border" />

            {events.map((event, index) => {
                const isFirst = index === 0;
                return (
                    <div key={event.id} className="relative pl-8">
                        {/* Timeline Connector */}
                        <div className={cn(
                            "absolute left-0 top-1 w-6 h-6 rounded-full flex items-center justify-center border text-xs",
                            isFirst ? "bg-primary text-primary-foreground border-primary" : "bg-card border-border text-muted-foreground"
                        )}>
                            <EventIcon type={event.type} />
                        </div>

                        <div className="bg-secondary/20 rounded-lg p-3 border border-border/50 text-sm">
                            <div className="flex justify-between items-start mb-1">
                                <span className={cn("font-medium", isFirst ? "text-primary" : "text-foreground")}>
                                    {formatEventType(event.type)}
                                </span>
                                <span className="text-xs text-muted-foreground whitespace-nowrap">
                                    {format(new Date(event.createdAt), 'MMM d, h:mm a')}
                                </span>
                            </div>

                            <EventDetails event={event} />

                            <div className="mt-2 text-xs text-muted-foreground flex items-center gap-1">
                                <div className="w-4 h-4 rounded-full bg-secondary border border-border flex items-center justify-center text-[10px]">
                                    {(event.createdBy?.name || 'U')[0]}
                                </div>
                                <span>{event.createdBy?.name || 'System'}</span>
                            </div>
                        </div>
                    </div>
                );
            })}
        </div>
    );
}

function EventIcon({ type }: { type: string }) {
    switch (type) {
        case 'MOVE': return <Move className="w-3 h-3" />;
        case 'CREATED': return <Sprout className="w-3 h-3" />;
        case 'DESTROY': return <Trash2 className="w-3 h-3" />;
        case 'NOTE': return <FileText className="w-3 h-3" />;
        case 'COMPLIANCE_CHECK': return <CheckCircle className="w-3 h-3" />;
        case 'HARVEST': return <Scissors className="w-3 h-3" />;
        default: return <div className="w-2 h-2 rounded-full bg-current" />;
    }
}

function formatEventType(type: string) {
    return type.replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, l => l.toUpperCase());
}

function EventDetails({ event }: { event: PlantLifecycleEvent }) {
    if (event.type === 'MOVE') {
        return (
            <div className="flex items-center gap-2 text-xs text-muted-foreground">
                <span className="bg-background px-1.5 py-0.5 rounded border border-border">{event.fromAddress || 'Origin'}</span>
                <ArrowRight className="w-3 h-3" />
                <span className="bg-background px-1.5 py-0.5 rounded border border-border text-foreground">{event.toAddress}</span>
            </div>
        );
    }

    if (event.type === 'NOTE' && event.metadata?.content) {
        return <p className="text-xs italic text-muted-foreground">"{event.metadata.content}"</p>;
    }

    if (event.metadata && Object.keys(event.metadata).length > 0) {
        return (
            <div className="text-xs text-muted-foreground mt-1 bg-background/50 p-1.5 rounded border border-border/50 font-mono">
                {JSON.stringify(event.metadata).slice(0, 50)}
            </div>
        );
    }

    return null;
}
