'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 { Avatar } from 'primereact/avatar';
import { Divider } from 'primereact/divider';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Tag } from 'primereact/tag';
import { clientService } from '@/services/api';
import type { Client, Chantier, Facture } from '@/types/btp';

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

  const [client, setClient] = useState<Client | null>(null);
  const [loading, setLoading] = useState(true);

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

  const loadClient = async () => {
    try {
      setLoading(true);
      const data = await clientService.getById(id);
      setClient(data);
    } catch (error) {
      console.error('Erreur lors du chargement du client:', 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 statutChantierTemplate = (rowData: Chantier) => {
    const severity = rowData.statut === 'EN_COURS' ? 'warning' :
                     rowData.statut === 'TERMINE' ? 'success' : 'info';
    return <Tag value={rowData.statut} severity={severity} />;
  };

  const statutFactureTemplate = (rowData: Facture) => {
    const severity = rowData.statut === 'PAYEE' ? 'success' :
                     rowData.statut === 'ENVOYEE' || rowData.statut === 'BROUILLON' ? 'warning' :
                     rowData.statut === 'PARTIELLEMENT_PAYEE' ? 'info' : 'danger';
    return <Tag value={rowData.statut} severity={severity} />;
  };

  if (loading || !client) {
    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('/clients')}
                tooltip="Retour"
              />
              <Avatar label={client.nom[0]} size="xlarge" shape="circle" className="mr-3" />
              <div>
                <h2 className="m-0">{client.nom} {client.prenom}</h2>
                <p className="text-600 m-0">{client.entreprise || 'Particulier'}</p>
              </div>
            </div>
            <Button
              icon="pi pi-pencil"
              label="Modifier"
              className="p-button-outlined"
            />
          </div>

          <Divider />

          <div className="grid">
            <div className="col-12 md:col-6">
              <h3>Coordonnées</h3>
              <div className="flex align-items-center mb-2">
                <i className="pi pi-envelope mr-2"></i>
                <span>{client.email}</span>
              </div>
              <div className="flex align-items-center mb-2">
                <i className="pi pi-phone mr-2"></i>
                <span>{client.telephone}</span>
              </div>
              <div className="flex align-items-center mb-2">
                <i className="pi pi-map-marker mr-2"></i>
                <span>{client.adresse}, {client.codePostal} {client.ville}</span>
              </div>
            </div>

            <div className="col-12 md:col-6">
              <h3>Informations supplémentaires</h3>
              <div className="mb-2"><strong>SIRET:</strong> {client.siret || 'N/A'}</div>
              <div className="mb-2"><strong>N° TVA:</strong> {client.numeroTVA || 'N/A'}</div>
              <div className="mb-2"><strong>Date de création:</strong> {new Date(client.dateCreation).toLocaleDateString('fr-FR')}</div>
            </div>
          </div>
        </Card>
      </div>

      <div className="col-12">
        <Card title="Activités">
          <p className="text-600">
            Les chantiers et factures associés à ce client seront affichés ici une fois la relation établie dans le backend.
          </p>
          <div className="flex gap-2 mt-3">
            <Button label="Voir les chantiers" icon="pi pi-home" className="p-button-outlined" onClick={() => router.push('/chantiers')} />
            <Button label="Voir les factures" icon="pi pi-file" className="p-button-outlined" onClick={() => router.push('/factures')} />
          </div>
        </Card>
      </div>
    </div>
  );
}
