'use client';

import { useState, useEffect, useCallback } from 'react';
import { FileText, Fuel } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { getImportsByLayoutName } from '@/app/actions/imports';
import { TerraTechImportsTable } from '@/app/components/terratech/TerraTechImportsTable';
import { TerraTechSummaryDialog } from '@/app/components/terratech/TerraTechSummaryDialog';
import { useToast } from '@/hooks/use-toast';

interface Import {
    id: number;
    name: string;
    importDate: string;
    layoutId: number;
    layout: {
        id: number;
        name: string;
    };
}

interface RawImportData {
    id: number;
    name: string;
    importDate: Date | string;
    layoutId: number;
    layout: {
        id: number;
        name: string;
    };
}

const LAYOUT_NAME = 'TerraTech - GasOilWater Summary';

export default function TerraTechFacilitySummariesPage() {
    const [imports, setImports] = useState<Import[]>([]);
    const [loading, setLoading] = useState(true);
    const [summaryDialogOpen, setSummaryDialogOpen] = useState(false);
    const [selectedImportId, setSelectedImportId] = useState<number | null>(null);
    const { toast } = useToast();

    const loadImports = useCallback(async () => {
        try {
            const result = await getImportsByLayoutName(LAYOUT_NAME);
            if (result.success && result.data) {
                const transformedImports = result.data.map((item: RawImportData) => ({
                    id: item.id,
                    name: item.name,
                    importDate: item.importDate instanceof Date
                        ? item.importDate.toISOString()
                        : String(item.importDate),
                    layoutId: item.layoutId,
                    layout: {
                        id: item.layout.id,
                        name: item.layout.name,
                    },
                }));
                setImports(transformedImports);
            } else {
                toast({
                    title: 'Error',
                    description: result.error || 'Failed to load imports',
                    variant: 'destructive',
                });
                setImports([]);
            }
        } catch {
            toast({
                title: 'Error',
                description: 'Failed to load imports',
                variant: 'destructive',
            });
        } finally {
            setLoading(false);
        }
    }, [toast]);

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

    function handleViewSummary(importRecord: Import) {
        setSelectedImportId(importRecord.id);
        setSummaryDialogOpen(true);
    }

    if (loading) {
        return (
            <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800">
                <div className="container mx-auto px-4 py-8">
                    <div className="flex justify-center">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800">
            <div className="container mx-auto px-4 py-8">
                <div className="flex justify-between items-center mb-8">
                    <div className="flex items-center gap-4">
                        <div className="bg-amber-500 w-12 h-12 rounded-full flex items-center justify-center text-white">
                            <Fuel className="w-6 h-6" />
                        </div>
                        <div>
                            <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
                                TerraTech Facility Summaries
                            </h1>
                            <p className="text-gray-600 dark:text-gray-300">
                                View Gas, Oil, and Water production summaries for imported data
                            </p>
                        </div>
                    </div>
                </div>

                {imports.length === 0 ? (
                    <Card className="dark:bg-gray-800 dark:border-gray-700">
                        <CardContent className="flex flex-col items-center justify-center py-12">
                            <FileText className="h-12 w-12 text-muted-foreground mb-4" />
                            <h3 className="text-lg font-semibold mb-2 text-gray-900 dark:text-white">No imports found</h3>
                            <p className="text-muted-foreground mb-4 dark:text-gray-300 text-center">
                                No imports using the &quot;{LAYOUT_NAME}&quot; layout configuration were found.
                                <br />
                                Import data using this layout to see it here.
                            </p>
                        </CardContent>
                    </Card>
                ) : (
                    <div className="w-full">
                        <TerraTechImportsTable
                            data={imports}
                            onViewSummary={handleViewSummary}
                        />
                    </div>
                )}

                <TerraTechSummaryDialog
                    open={summaryDialogOpen}
                    onOpenChange={setSummaryDialogOpen}
                    importId={selectedImportId || 0}
                />
            </div>
        </div>
    );
}
