'use client';

import React, { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { Card } from 'primereact/card';
import { Button } from 'primereact/button';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { ProgressBar } from 'primereact/progressbar';
import { Chart } from 'primereact/chart';
import { Tag } from 'primereact/tag';
import { budgetService } from '@/services/api';

interface BudgetChantier {
  id: number;
  chantierNom: string;
  budgetTotal: number;
  depenseTotal: number;
  resteAEngager: number;
  lignesBudget: LigneBudget[];
}

interface LigneBudget {
  id: number;
  categorie: string;
  budgetPrevu: number;
  depenseReel: number;
  ecart: number;
  pourcentageUtilisation: number;
}

export default function ChantierBudgetPage() {
  const params = useParams();
  const router = useRouter();
  const id = params.id as string;

  const [budget, setBudget] = useState<BudgetChantier | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (id) {
      loadBudget();
    }
  }, [id]);

  const loadBudget = async () => {
    try {
      setLoading(true);
      const data = await budgetService.getByChantier(id);
      setBudget(data);
    } catch (error) {
      console.error('Erreur lors du chargement du budget:', error);
      // L'intercepteur API gérera automatiquement la redirection si 401
    } finally {
      setLoading(false);
    }
  };

  const formatMontant = (montant: number) => {
    return new Intl.NumberFormat('fr-FR', {
      style: 'currency',
      currency: 'EUR'
    }).format(montant);
  };

  const montantBodyTemplate = (rowData: LigneBudget, field: string) => {
    const value = (rowData as any)[field];
    return formatMontant(value);
  };

  const ecartBodyTemplate = (rowData: LigneBudget) => {
    const severity = rowData.ecart >= 0 ? 'success' : 'danger';
    const icon = rowData.ecart >= 0 ? 'pi-check' : 'pi-exclamation-triangle';

    return (
      <Tag
        value={formatMontant(Math.abs(rowData.ecart))}
        severity={severity}
        icon={`pi ${icon}`}
      />
    );
  };

  const progressionBodyTemplate = (rowData: LigneBudget) => {
    const severity = rowData.pourcentageUtilisation > 100 ? 'danger' :
                    rowData.pourcentageUtilisation > 80 ? 'warning' : 'success';

    return (
      <div>
        <ProgressBar value={rowData.pourcentageUtilisation} showValue={false} color={severity === 'danger' ? '#ef4444' : severity === 'warning' ? '#f59e0b' : '#10b981'} />
        <span className="text-sm">{rowData.pourcentageUtilisation.toFixed(1)}%</span>
      </div>
    );
  };

  const getChartData = () => {
    if (!budget) return null;

    return {
      labels: budget.lignesBudget?.map(l => l.categorie) || [],
      datasets: [
        {
          label: 'Budget prévu',
          backgroundColor: '#42A5F5',
          data: budget.lignesBudget?.map(l => l.budgetPrevu) || []
        },
        {
          label: 'Dépenses réelles',
          backgroundColor: '#FFA726',
          data: budget.lignesBudget?.map(l => l.depenseReel) || []
        }
      ]
    };
  };

  const getChartOptions = () => {
    return {
      maintainAspectRatio: false,
      aspectRatio: 0.8,
      plugins: {
        legend: {
          position: 'top',
        }
      },
      scales: {
        y: {
          beginAtZero: true,
          ticks: {
            callback: function(value: any) {
              return formatMontant(value);
            }
          }
        }
      }
    };
  };

  const getPourcentageUtilisation = () => {
    if (!budget || budget.budgetTotal === 0) return 0;
    return (budget.depenseTotal / budget.budgetTotal) * 100;
  };

  return (
    <div className="grid">
      <div className="col-12">
        <div className="flex justify-content-between align-items-center mb-3">
          <div className="flex align-items-center">
            <Button
              icon="pi pi-arrow-left"
              className="p-button-text mr-2"
              onClick={() => router.push(`/chantiers/${id}`)}
              tooltip="Retour"
            />
            <h2 className="m-0">Budget du chantier</h2>
          </div>
          <Button
            label="Ajouter une ligne"
            icon="pi pi-plus"
            className="p-button-success"
          />
        </div>
      </div>

      {/* Vue d'ensemble */}
      <div className="col-12 lg:col-4">
        <Card title="Budget total">
          <div className="text-center">
            <div className="text-5xl font-bold text-primary mb-2">
              {budget ? formatMontant(budget.budgetTotal) : formatMontant(0)}
            </div>
            <div className="text-600">Montant budgété</div>
          </div>
        </Card>
      </div>

      <div className="col-12 lg:col-4">
        <Card title="Dépenses réelles">
          <div className="text-center">
            <div className="text-5xl font-bold text-orange-500 mb-2">
              {budget ? formatMontant(budget.depenseTotal) : formatMontant(0)}
            </div>
            <div className="text-600">Montant dépensé</div>
          </div>
        </Card>
      </div>

      <div className="col-12 lg:col-4">
        <Card title="Reste à engager">
          <div className="text-center">
            <div className="text-5xl font-bold text-green-500 mb-2">
              {budget ? formatMontant(budget.resteAEngager) : formatMontant(0)}
            </div>
            <div className="text-600">Montant disponible</div>
          </div>
        </Card>
      </div>

      {/* Progression */}
      <div className="col-12">
        <Card title="Utilisation du budget">
          <div className="mb-2">
            <ProgressBar
              value={getPourcentageUtilisation()}
              showValue={false}
              color={getPourcentageUtilisation() > 100 ? '#ef4444' : getPourcentageUtilisation() > 80 ? '#f59e0b' : '#10b981'}
              style={{ height: '30px' }}
            />
          </div>
          <div className="text-center text-xl font-bold">
            {getPourcentageUtilisation().toFixed(1)}% du budget utilisé
          </div>
        </Card>
      </div>

      {/* Graphique */}
      <div className="col-12 lg:col-6">
        <Card title="Comparaison Budget / Dépenses">
          <Chart type="bar" data={getChartData()} options={getChartOptions()} style={{ height: '400px' }} />
        </Card>
      </div>

      {/* Répartition */}
      <div className="col-12 lg:col-6">
        <Card title="Répartition du budget">
          <Chart
            type="doughnut"
            data={{
              labels: budget?.lignesBudget?.map(l => l.categorie) || [],
              datasets: [{
                data: budget?.lignesBudget?.map(l => l.budgetPrevu) || [],
                backgroundColor: [
                  '#42A5F5',
                  '#66BB6A',
                  '#FFA726',
                  '#EF5350',
                  '#AB47BC',
                  '#26C6DA'
                ]
              }]
            }}
            style={{ height: '400px' }}
          />
        </Card>
      </div>

      {/* Tableau détaillé */}
      <div className="col-12">
        <Card title="Détail par catégorie">
          <DataTable
            value={budget?.lignesBudget || []}
            loading={loading}
            responsiveLayout="scroll"
            emptyMessage="Aucune ligne budgétaire"
          >
            <Column field="categorie" header="Catégorie" sortable />
            <Column
              field="budgetPrevu"
              header="Budget prévu"
              body={(rowData) => montantBodyTemplate(rowData, 'budgetPrevu')}
              sortable
            />
            <Column
              field="depenseReel"
              header="Dépenses réelles"
              body={(rowData) => montantBodyTemplate(rowData, 'depenseReel')}
              sortable
            />
            <Column
              field="ecart"
              header="Écart"
              body={ecartBodyTemplate}
              sortable
            />
            <Column
              field="pourcentageUtilisation"
              header="Utilisation"
              body={progressionBodyTemplate}
              sortable
            />
            <Column
              header="Actions"
              body={() => (
                <div className="flex gap-2">
                  <Button icon="pi pi-pencil" className="p-button-text p-button-sm" />
                  <Button icon="pi pi-trash" className="p-button-text p-button-sm p-button-danger" />
                </div>
              )}
            />
          </DataTable>
        </Card>
      </div>
    </div>
  );
}
