'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';

interface Client {
  id: number;
  nom: string;
  email: string;
  telephone: string;
  adresse: string;
  ville: string;
  codePostal: string;
  typeClient: string;
  dateCreation: string;
  chantiers: Chantier[];
  factures: Facture[];
}

interface Chantier {
  id: number;
  nom: string;
  statut: string;
  dateDebut: string;
  budget: number;
}

interface Facture {
  id: number;
  numero: string;
  montant: number;
  dateEmission: string;
  statut: string;
}

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 API_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.lions.dev/btpxpress';
      const response = await fetch(`${API_URL}/api/v1/clients/${id}`);

      if (response.ok) {
        const data = await response.json();
        setClient(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 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 === 'EN_ATTENTE' ? 'warning' : '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}</h2>
                <p className="text-600 m-0">{client.typeClient}</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>Statistiques</h3>
              <div className="grid">
                <div className="col-6">
                  <Card className="text-center">
                    <div className="text-600">Chantiers</div>
                    <div className="text-2xl font-bold">{client.chantiers?.length || 0}</div>
                  </Card>
                </div>
                <div className="col-6">
                  <Card className="text-center">
                    <div className="text-600">Factures</div>
                    <div className="text-2xl font-bold">{client.factures?.length || 0}</div>
                  </Card>
                </div>
              </div>
            </div>
          </div>
        </Card>
      </div>

      <div className="col-12">
        <Card>
          <TabView>
            <TabPanel header="Chantiers" leftIcon="pi pi-home mr-2">
              <DataTable value={client.chantiers || []} emptyMessage="Aucun chantier">
                <Column field="nom" header="Nom" sortable />
                <Column field="statut" header="Statut" body={statutChantierTemplate} sortable />
                <Column field="dateDebut" header="Date début" sortable />
                <Column
                  field="budget"
                  header="Budget"
                  body={(rowData) => formatMontant(rowData.budget)}
                  sortable
                />
                <Column
                  header="Actions"
                  body={(rowData) => (
                    <Button
                      icon="pi pi-eye"
                      className="p-button-text p-button-sm"
                      onClick={() => router.push(`/chantiers/${rowData.id}`)}
                    />
                  )}
                />
              </DataTable>
            </TabPanel>

            <TabPanel header="Factures" leftIcon="pi pi-file mr-2">
              <DataTable value={client.factures || []} emptyMessage="Aucune facture">
                <Column field="numero" header="Numéro" sortable />
                <Column
                  field="montant"
                  header="Montant"
                  body={(rowData) => formatMontant(rowData.montant)}
                  sortable
                />
                <Column field="dateEmission" header="Date" sortable />
                <Column field="statut" header="Statut" body={statutFactureTemplate} sortable />
                <Column
                  header="Actions"
                  body={(rowData) => (
                    <Button
                      icon="pi pi-eye"
                      className="p-button-text p-button-sm"
                      onClick={() => router.push(`/factures/${rowData.id}`)}
                    />
                  )}
                />
              </DataTable>
            </TabPanel>

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