'use client';

import React, { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { Card } from 'primereact/card';
import { TabView, TabPanel } from 'primereact/tabview';
import { Button } from 'primereact/button';
import { Tag } from 'primereact/tag';
import { Calendar } from 'primereact/calendar';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Timeline } from 'primereact/timeline';

interface Materiel {
  id: number;
  nom: string;
  reference: string;
  type: string;
  marque: string;
  modele: string;
  statut: string;
  dateAchat: string;
  prixAchat: number;
  tauxJournalier: number;
  disponibilite: string;
  reservations: Reservation[];
  maintenances: Maintenance[];
}

interface Reservation {
  id: number;
  chantier: string;
  dateDebut: string;
  dateFin: string;
  statut: string;
}

interface Maintenance {
  id: number;
  type: string;
  date: string;
  description: string;
  cout: number;
}

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

  const [materiel, setMateriel] = useState<Materiel | null>(null);
  const [loading, setLoading] = useState(true);

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

  const loadMateriel = async () => {
    try {
      setLoading(true);
      const API_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.lions.dev/btpxpress';
      const response = await fetch(`${API_URL}/api/v1/materiels/${id}`);

      if (response.ok) {
        const data = await response.json();
        setMateriel(data);
      }
    } catch (error) {
      console.error('Erreur:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const getStatutSeverity = (statut: string) => {
    switch (statut?.toUpperCase()) {
      case 'DISPONIBLE':
        return 'success';
      case 'EN_UTILISATION':
        return 'warning';
      case 'EN_MAINTENANCE':
        return 'info';
      case 'HORS_SERVICE':
        return 'danger';
      default:
        return 'info';
    }
  };

  const statutTemplate = (rowData: Reservation) => {
    return <Tag value={rowData.statut} severity={getStatutSeverity(rowData.statut)} />;
  };

  if (loading || !materiel) {
    return <div>Chargement...</div>;
  }

  return (
    <div className="grid">
      <div className="col-12">
        <Card>
          <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('/materiels')}
                tooltip="Retour"
              />
              <div>
                <h2 className="m-0">{materiel.nom}</h2>
                <p className="text-600 m-0">{materiel.reference}</p>
              </div>
            </div>
            <div>
              <Tag
                value={materiel.statut}
                severity={getStatutSeverity(materiel.statut)}
                className="mr-2"
              />
              <Button
                icon="pi pi-pencil"
                label="Modifier"
                className="p-button-outlined"
              />
            </div>
          </div>

          <div className="grid">
            <div className="col-12 md:col-6">
              <h3>Informations</h3>
              <div className="mb-2"><strong>Type:</strong> {materiel.type}</div>
              <div className="mb-2"><strong>Marque:</strong> {materiel.marque}</div>
              <div className="mb-2"><strong>Modèle:</strong> {materiel.modele}</div>
              <div className="mb-2"><strong>Date d'achat:</strong> {materiel.dateAchat}</div>
              <div className="mb-2"><strong>Prix d'achat:</strong> {formatMontant(materiel.prixAchat)}</div>
              <div className="mb-2"><strong>Tarif journalier:</strong> {formatMontant(materiel.tauxJournalier)}</div>
            </div>

            <div className="col-12 md:col-6">
              <h3>Disponibilité</h3>
              <Calendar inline showWeek />
            </div>
          </div>
        </Card>
      </div>

      <div className="col-12">
        <Card>
          <TabView>
            <TabPanel header="Réservations" leftIcon="pi pi-calendar mr-2">
              <DataTable value={materiel.reservations || []} emptyMessage="Aucune réservation">
                <Column field="chantier" header="Chantier" sortable />
                <Column field="dateDebut" header="Date début" sortable />
                <Column field="dateFin" header="Date fin" sortable />
                <Column field="statut" header="Statut" body={statutTemplate} sortable />
                <Column
                  header="Actions"
                  body={() => (
                    <Button icon="pi pi-eye" className="p-button-text p-button-sm" />
                  )}
                />
              </DataTable>
            </TabPanel>

            <TabPanel header="Maintenances" leftIcon="pi pi-wrench mr-2">
              <Timeline
                value={materiel.maintenances || []}
                content={(item: Maintenance) => (
                  <Card>
                    <div><strong>{item.type}</strong></div>
                    <div className="text-600">{item.date}</div>
                    <p>{item.description}</p>
                    <div><strong>Coût:</strong> {formatMontant(item.cout)}</div>
                  </Card>
                )}
              />
            </TabPanel>

            <TabPanel header="Documents" leftIcon="pi pi-folder mr-2">
              <p>Documents techniques et certificats</p>
            </TabPanel>
          </TabView>
        </Card>
      </div>
    </div>
  );
}
