import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { History, Loader2 } from 'lucide-react';
import { WorkflowHistorySummaryDto } from '@/api/schema.gen';
import { z } from 'zod';
import { client } from '@/api/client';

type WorkflowHistorySummary = z.infer<typeof WorkflowHistorySummaryDto>;

export function RecentReportsDropdown() {
    const [reports, setReports] = useState<WorkflowHistorySummary[]>([]);
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate();

    const loadReports = async () => {
        setLoading(true);
        try {
            // Using generated client to fetch history
            const data = await client.get_workflow_histories({ queries: { limit: 10 } });
            setReports(data);
        } catch (e) {
            console.error("Failed to load reports", e);
            setReports([]);
        } finally {
            setLoading(false);
        }
    };

    return (
        <DropdownMenu onOpenChange={(open) => { if(open) loadReports(); }}>
            <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="sm" className="gap-2 text-muted-foreground hover:text-foreground">
                    <History className="h-4 w-4" />
                    <span className="hidden sm:inline">History</span>
                </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-80 max-h-[400px] overflow-y-auto">
                <DropdownMenuLabel>Recent Reports</DropdownMenuLabel>
                <DropdownMenuSeparator />
                {loading ? (
                    <div className="p-4 flex justify-center">
                        <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
                    </div>
                ) : reports.length === 0 ? (
                    <div className="p-4 text-center text-sm text-muted-foreground">No recent reports</div>
                ) : (
                    reports.map((report) => (
                        <DropdownMenuItem 
                            key={report.request_id} 
                            onClick={() => navigate(`/history/${report.request_id}`)}
                            className="flex flex-col items-start gap-1 cursor-pointer py-3"
                        >
                            <div className="font-medium flex justify-between w-full">
                                <span>{report.symbol} <span className="text-xs text-muted-foreground font-normal">({report.market})</span></span>
                                <span className="text-xs font-normal text-muted-foreground">{new Date(report.start_time).toLocaleDateString()}</span>
                            </div>
                            <div className="flex justify-between w-full text-xs text-muted-foreground">
                                <span>{report.template_id || 'Default'}</span>
                                <span className={report.status === 'Completed' ? 'text-green-600' : report.status === 'Failed' ? 'text-destructive' : 'text-amber-600'}>{report.status}</span>
                            </div>
                        </DropdownMenuItem>
                    ))
                )}
            </DropdownMenuContent>
        </DropdownMenu>
    );
}
