import React, { useEffect, useState } from 'react';
import { getProjectAnalysis, type AnalysisResult } from '../services/analysisService';
import { AlertCircle, CheckCircle, XCircle } from 'lucide-react';

interface Props {
    projectId: string;
}

export const AnalysisDashboard: React.FC<Props> = ({ projectId }) => {
    const [analysis, setAnalysis] = useState<AnalysisResult[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        const fetchAnalysis = async () => {
            try {
                const response = await getProjectAnalysis(projectId);
                setAnalysis(response.data);
                setLoading(false);
            } catch (err: unknown) {
                const errorMessage = err instanceof Error ? err.message : 'Erro ao carregar análise';
                setError(errorMessage);
                setLoading(false);
            }
        };

        fetchAnalysis();
    }, [projectId]);

    if (loading) return <div className="text-center p-8">Carregando análise...</div>;
    if (error) return <div className="text-error p-4">{error}</div>;

    if (analysis.length === 0) {
        return (
            <div className="text-center p-8 text-text-secondary">
                Nenhum dado suficiente para análise. Cadastre registros de aplicação e esquemas de pintura.
            </div>
        );
    }

    const renderStatusIcon = (status: 'approved' | 'warning' | 'critical') => {
        if (status === 'approved') return <CheckCircle className="text-success w-5 h-5" />;
        if (status === 'warning') return <AlertCircle className="text-warning w-5 h-5" />;
        return <XCircle className="text-error w-5 h-5" />;
    };

    return (
        <div className="space-y-6">
            <div>
                <h2 className="text-xl font-bold text-text-main mb-2">Relatório de Conformidade Técnica</h2>
                <p className="text-text-secondary">Comparativo entre valores teóricos (Esquema) e reais (Aplicação/Inspeção)</p>
            </div>

            <div className="bg-surface rounded-xl shadow-sm border border-border overflow-hidden">
                <div className="overflow-x-auto">
                    <table className="w-full text-left">
                        <thead className="bg-surface-hover text-text-secondary text-sm font-medium">
                            <tr>
                                <th className="p-4">Peça / Lote</th>
                                <th className="p-4">Esquema</th>
                                <th className="p-4 text-center">Rendimento (m²/L)</th>
                                <th className="p-4 text-center">Diluição (%)</th>
                                <th className="p-4 text-center">Espessura (μm)</th>
                                <th className="p-4 text-center">Status Global</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-border">
                            {analysis.map((item, index) => (
                                <tr key={index} className="hover:bg-surface-soft transition-colors">
                                    <td className="p-4 font-medium text-text-main">{item.pieceDescription}</td>
                                    <td className="p-4 text-text-secondary text-sm">
                                        {item.schemeName}
                                        <div className="text-xs text-text-muted">{item.schemeType}</div>
                                    </td>

                                    {/* Yield */}
                                    <td className="p-4 text-center">
                                        <div className="flex flex-col items-center">
                                            <div className="flex items-center gap-2">
                                                <span className="font-semibold">{item.realYield}</span>
                                                {renderStatusIcon(item.yieldStatus)}
                                            </div>
                                            <span className="text-xs text-text-muted">Meta: {item.theoreticalYield}</span>
                                            <span className={`text-xs ${item.yieldStatus === 'critical' ? 'text-error' : item.yieldStatus === 'warning' ? 'text-warning' : 'text-success'}`}>
                                                {item.yieldVariance > 0 ? '+' : ''}{item.yieldVariance}%
                                            </span>
                                        </div>
                                    </td>

                                    {/* Dilution */}
                                    <td className="p-4 text-center">
                                        <div className="flex flex-col items-center">
                                            <div className="flex items-center gap-2">
                                                <span className="font-semibold">{item.realDilution}%</span>
                                                {renderStatusIcon(item.dilutionStatus)}
                                            </div>
                                            <span className="text-xs text-text-muted">Max: {item.targetDilution}%</span>
                                        </div>
                                    </td>

                                    {/* DFT */}
                                    <td className="p-4 text-center">
                                        <div className="flex flex-col items-center">
                                            <div className="flex items-center gap-2">
                                                <span className="font-semibold">{item.realDFT}</span>
                                                {renderStatusIcon(item.dftStatus)}
                                            </div>
                                            <span className="text-xs text-text-muted">{item.minDFT} - {item.maxDFT}</span>
                                        </div>
                                    </td>

                                    {/* Overall Status */}
                                    <td className="p-4 text-center">
                                        {(item.yieldStatus === 'critical' || item.dftStatus === 'critical') ? (
                                            <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-error/10 text-error">
                                                REPROVADO
                                            </span>
                                        ) : (item.yieldStatus === 'warning' || item.dftStatus === 'warning') ? (
                                            <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-warning/10 text-warning">
                                                ATENÇÃO
                                            </span>
                                        ) : (
                                            <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-success/10 text-success">
                                                APROVADO
                                            </span>
                                        )}
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm text-text-secondary">
                <div className="bg-surface p-4 rounded-lg border border-border">
                    <div className="flex items-center gap-2 mb-2 font-medium text-text-main">
                        <CheckCircle className="text-success w-4 h-4" /> Aprovado
                    </div>
                    Variação tolerável (até 20%) em relação aos parâmetros teóricos e normas.
                </div>
                <div className="bg-surface p-4 rounded-lg border border-border">
                    <div className="flex items-center gap-2 mb-2 font-medium text-text-main">
                        <AlertCircle className="text-warning w-4 h-4" /> Atenção
                    </div>
                    Variação moderada (20-30%). Requer acompanhamento técnico para ajustes.
                </div>
                <div className="bg-surface p-4 rounded-lg border border-border">
                    <div className="flex items-center gap-2 mb-2 font-medium text-text-main">
                        <XCircle className="text-error w-4 h-4" /> Crítico
                    </div>
                    Desvio significativo (&gt;30%) ou fora das normas. Risco de falha do revestimento.
                </div>
            </div>
        </div>
    );
};
