"use client";

import { useEffect, useState } from "react";
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { getTerraTechFacilitySummary, TerraTechSummaryRow } from "@/app/actions/imports";
import { Fuel, AlertTriangle } from "lucide-react";

interface TerraTechSummaryDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    importId: number;
}

interface SummaryData {
    importId: number;
    importName: string;
    layoutName: string;
    rows: TerraTechSummaryRow[];
}

export function TerraTechSummaryDialog({ open, onOpenChange, importId }: TerraTechSummaryDialogProps) {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [summaryData, setSummaryData] = useState<SummaryData | null>(null);

    useEffect(() => {
        if (open && importId) {
            loadSummary();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [open, importId]);

    async function loadSummary() {
        setLoading(true);
        setError(null);
        try {
            const result = await getTerraTechFacilitySummary(importId);
            if (result.success && result.data) {
                setSummaryData(result.data);
            } else {
                setError(result.error || 'Failed to load summary');
            }
        } catch {
            setError('An unexpected error occurred');
        } finally {
            setLoading(false);
        }
    }

    function formatNumber(value: number | string | null | undefined, decimals: number = 2): string {
        if (value === null || value === undefined) return '-';
        const num = typeof value === 'string' ? parseFloat(value) : value;
        if (isNaN(num)) return '-';
        return num.toLocaleString('en-US', { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
    }

    function formatPercent(value: number | string | null | undefined): string {
        if (value === null || value === undefined) return '-';
        const num = typeof value === 'string' ? parseFloat(value) : value;
        if (isNaN(num)) return '-';
        return `${num.toFixed(1)}%`;
    }

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-[95vw] max-h-[90vh] dark:bg-gray-800 dark:border-gray-700">
                <DialogHeader>
                    <DialogTitle className="flex items-center gap-2 text-gray-900 dark:text-white">
                        <div className="bg-amber-500 w-8 h-8 rounded-full flex items-center justify-center text-white">
                            <Fuel className="w-4 h-4" />
                        </div>
                        Facility Summary
                        {summaryData && (
                            <Badge variant="outline" className="ml-2">
                                {summaryData.importName}
                            </Badge>
                        )}
                    </DialogTitle>
                </DialogHeader>

                {loading && (
                    <div className="flex justify-center py-12">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-amber-500"></div>
                    </div>
                )}

                {error && (
                    <div className="flex flex-col items-center justify-center py-12 text-red-500">
                        <AlertTriangle className="h-8 w-8 mb-2" />
                        <p>{error}</p>
                    </div>
                )}

                {!loading && !error && summaryData && (
                    <div className="h-[70vh] overflow-auto">
                        <div className="pr-4">
                            <div className="mb-4 text-sm text-gray-600 dark:text-gray-300">
                                Total records: <strong>{summaryData.rows.length}</strong>
                            </div>
                            <Table>
                                <TableHeader>
                                    <TableRow className="dark:border-gray-700">
                                        <TableHead className="sticky left-0 bg-white dark:bg-gray-800 z-10">Well Name</TableHead>
                                        <TableHead>CorpID</TableHead>
                                        <TableHead>Facility ID</TableHead>
                                        <TableHead className="text-right">Gas</TableHead>
                                        <TableHead className="text-right">Oil</TableHead>
                                        <TableHead className="text-right">Water</TableHead>
                                        <TableHead>State</TableHead>
                                        <TableHead>County</TableHead>
                                        <TableHead className="text-right">Days Q1</TableHead>
                                        <TableHead className="text-right">Days Q2</TableHead>
                                        <TableHead className="text-right">Days Q3</TableHead>
                                        <TableHead className="text-right">Days Q4</TableHead>
                                        <TableHead className="text-right">Q1 %</TableHead>
                                        <TableHead className="text-right">Q2 %</TableHead>
                                        <TableHead className="text-right">Q3 %</TableHead>
                                        <TableHead className="text-right">Q4 %</TableHead>
                                        <TableHead className="text-right">Gas-corr</TableHead>
                                        <TableHead className="text-right">Oil-corr</TableHead>
                                        <TableHead className="text-right">Water-corr</TableHead>
                                        <TableHead>Missing Facility ID</TableHead>
                                        <TableHead>Missing County</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {summaryData.rows.length === 0 ? (
                                        <TableRow>
                                            <TableCell colSpan={21} className="h-24 text-center">
                                                No summary data available for this import.
                                            </TableCell>
                                        </TableRow>
                                    ) : (
                                        summaryData.rows.map((row, index) => (
                                            <TableRow key={index} className="dark:border-gray-700">
                                                <TableCell className="sticky left-0 bg-white dark:bg-gray-800 font-medium">
                                                    {row.wellName || '-'}
                                                </TableCell>
                                                <TableCell>{row.corpId || '-'}</TableCell>
                                                <TableCell>
                                                    {row.facilityId || (
                                                        <span className="text-amber-500">-</span>
                                                    )}
                                                </TableCell>
                                                <TableCell className="text-right">{formatNumber(row.gas)}</TableCell>
                                                <TableCell className="text-right">{formatNumber(row.oil)}</TableCell>
                                                <TableCell className="text-right">{formatNumber(row.water)}</TableCell>
                                                <TableCell>{row.state || '-'}</TableCell>
                                                <TableCell>
                                                    {row.county || (
                                                        <span className="text-amber-500">-</span>
                                                    )}
                                                </TableCell>
                                                <TableCell className="text-right">{formatNumber(row.daysQ1, 0)}</TableCell>
                                                <TableCell className="text-right">{formatNumber(row.daysQ2, 0)}</TableCell>
                                                <TableCell className="text-right">{formatNumber(row.daysQ3, 0)}</TableCell>
                                                <TableCell className="text-right">{formatNumber(row.daysQ4, 0)}</TableCell>
                                                <TableCell className="text-right">{formatPercent(row.daysQ1Pct)}</TableCell>
                                                <TableCell className="text-right">{formatPercent(row.daysQ2Pct)}</TableCell>
                                                <TableCell className="text-right">{formatPercent(row.daysQ3Pct)}</TableCell>
                                                <TableCell className="text-right">{formatPercent(row.daysQ4Pct)}</TableCell>
                                                <TableCell className="text-right">{formatNumber(row.gasCorr)}</TableCell>
                                                <TableCell className="text-right">{formatNumber(row.oilCorr)}</TableCell>
                                                <TableCell className="text-right">{formatNumber(row.waterCorr)}</TableCell>
                                                <TableCell>
                                                    {row.isMissingFacilityId && (
                                                        <Badge variant="destructive" className="text-xs">Yes</Badge>
                                                    )}
                                                </TableCell>
                                                <TableCell>
                                                    {row.isMissingCounty && (
                                                        <Badge variant="destructive" className="text-xs">Yes</Badge>
                                                    )}
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    )}
                                </TableBody>
                            </Table>
                        </div>
                    </div>
                )}
            </DialogContent>
        </Dialog>
    );
}
