'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';
import { materielService } from '@/services/api';
import type { Materiel } from '@/types/btp';

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 data = await materielService.getById(id);
      setMateriel(data);
    } catch (error) {
      console.error('Erreur lors du chargement du matériel:', 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 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';
    }
  };


  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.numeroSerie || 'N/A'}</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 || 'N/A'}</div>
              <div className="mb-2"><strong>Modèle:</strong> {materiel.modele || 'N/A'}</div>
              <div className="mb-2"><strong>Date d'achat:</strong> {materiel.dateAchat || 'N/A'}</div>
              <div className="mb-2"><strong>Valeur d'achat:</strong> {formatMontant(materiel.valeurAchat || 0)}</div>
              <div className="mb-2"><strong>Coût d'utilisation:</strong> {formatMontant(materiel.coutUtilisation || 0)}</div>
            </div>

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

      <div className="col-12">
        <Card title="Historique d'utilisation">
          <p className="text-600">
            Les réservations et maintenances de ce matériel seront affichées ici une fois la relation établie dans le backend.
          </p>
          <div className="flex gap-2 mt-3">
            <Button label="Voir le planning" icon="pi pi-calendar" className="p-button-outlined" onClick={() => router.push('/planning')} />
            <Button label="Planifier une maintenance" icon="pi pi-wrench" className="p-button-outlined" />
          </div>
        </Card>
      </div>
    </div>
  );
}
