'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 { ProgressBar } from 'primereact/progressbar';
import { Divider } from 'primereact/divider';
import { Skeleton } from 'primereact/skeleton';
import { chantierService } from '@/services/api';
import type { Chantier } from '@/types/btp';

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

  const [chantier, setChantier] = useState<Chantier | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState(0);

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

  const loadChantier = async () => {
    try {
      setLoading(true);
      const data = await chantierService.getById(id);
      setChantier(data);
    } catch (error) {
      console.error('Erreur lors du chargement du chantier:', error);
      // L'intercepteur API gérera automatiquement la redirection si 401
      // TODO: Afficher un toast d'erreur pour les autres erreurs
    } finally {
      setLoading(false);
    }
  };

  const getStatutSeverity = (statut: string) => {
    switch (statut?.toUpperCase()) {
      case 'PLANIFIE':
        return 'info';
      case 'EN_COURS':
        return 'warning';
      case 'TERMINE':
        return 'success';
      case 'SUSPENDU':
        return 'danger';
      case 'ANNULE':
        return 'secondary';
      default:
        return 'info';
    }
  };

  const getStatutLabel = (statut: string) => {
    const labels: { [key: string]: string } = {
      'PLANIFIE': 'Planifié',
      'EN_COURS': 'En cours',
      'TERMINE': 'Terminé',
      'SUSPENDU': 'Suspendu',
      'ANNULE': 'Annulé'
    };
    return labels[statut] || statut;
  };

  const formatDate = (dateString: string) => {
    if (!dateString) return 'N/A';
    return new Date(dateString).toLocaleDateString('fr-FR');
  };

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

  if (loading) {
    return (
      <div className="grid">
        <div className="col-12">
          <Card>
            <Skeleton width="100%" height="150px" />
            <Divider />
            <Skeleton width="100%" height="300px" className="mt-3" />
          </Card>
        </div>
      </div>
    );
  }

  if (!chantier) {
    return (
      <div className="grid">
        <div className="col-12">
          <Card>
            <div className="text-center">
              <i className="pi pi-exclamation-triangle text-6xl text-orange-500 mb-3"></i>
              <h3>Chantier non trouvé</h3>
              <p>Le chantier demandé n'existe pas ou a été supprimé.</p>
              <Button
                label="Retour à la liste"
                icon="pi pi-arrow-left"
                onClick={() => router.push('/chantiers')}
                className="mt-3"
              />
            </div>
          </Card>
        </div>
      </div>
    );
  }

  return (
    <div className="grid">
      {/* En-tête du chantier */}
      <div className="col-12">
        <Card>
          <div className="flex justify-content-between align-items-center mb-3">
            <div>
              <Button
                icon="pi pi-arrow-left"
                className="p-button-text mr-2"
                onClick={() => router.push('/chantiers')}
                tooltip="Retour"
              />
              <span className="text-3xl font-bold">{chantier.nom}</span>
            </div>
            <div>
              <Tag
                value={getStatutLabel(chantier.statut)}
                severity={getStatutSeverity(chantier.statut)}
                className="mr-2"
              />
              <Button
                icon="pi pi-pencil"
                label="Modifier"
                className="p-button-outlined mr-2"
                onClick={() => router.push(`/chantiers/${id}/modifier`)}
              />
              <Button
                icon="pi pi-ellipsis-v"
                className="p-button-outlined"
              />
            </div>
          </div>

          <div className="grid">
            <div className="col-12 md:col-8">
              <p className="text-600 mb-3">{chantier.description}</p>

              <div className="flex align-items-center mb-2">
                <i className="pi pi-map-marker mr-2 text-600"></i>
                <span>{chantier.adresse}, {chantier.codePostal} {chantier.ville}</span>
              </div>

              <div className="flex align-items-center mb-2">
                <i className="pi pi-user mr-2 text-600"></i>
                <span><strong>Client:</strong> {chantier.client?.nom}</span>
              </div>

              <div className="flex align-items-center mb-2">
                <i className="pi pi-building mr-2 text-600"></i>
                <span><strong>Type:</strong> {chantier.typeChantier || 'N/A'}</span>
              </div>
            </div>

            <div className="col-12 md:col-4">
              <div className="surface-100 border-round p-3">
                <div className="mb-3">
                  <span className="text-600 text-sm">Progression</span>
                  <ProgressBar value={0} className="mt-2" />
                </div>

                <div className="mb-3">
                  <span className="text-600 text-sm">Début</span>
                  <div className="font-bold">{formatDate(chantier.dateDebut)}</div>
                </div>

                <div className="mb-3">
                  <span className="text-600 text-sm">Fin prévue</span>
                  <div className="font-bold">{formatDate(chantier.dateFinPrevue || '')}</div>
                </div>

                <div>
                  <span className="text-600 text-sm">Budget</span>
                  <div className="font-bold text-xl text-primary">{formatMontant(chantier.montantPrevu || 0)}</div>
                </div>
              </div>
            </div>
          </div>
        </Card>
      </div>

      {/* Onglets */}
      <div className="col-12">
        <Card>
          <TabView activeIndex={activeTab} onTabChange={(e) => setActiveTab(e.index)}>
            <TabPanel header="Vue d'ensemble" leftIcon="pi pi-home mr-2">
              <div className="grid">
                <div className="col-12 md:col-3">
                  <Card className="text-center">
                    <i className="pi pi-calendar text-4xl text-blue-500 mb-2"></i>
                    <div className="text-600 text-sm mb-1">Durée</div>
                    <div className="text-2xl font-bold">
                      {chantier.dateFinPrevue ? Math.ceil((new Date(chantier.dateFinPrevue).getTime() - new Date(chantier.dateDebut).getTime()) / (1000 * 60 * 60 * 24)) : 0} jours
                    </div>
                  </Card>
                </div>

                <div className="col-12 md:col-3">
                  <Card className="text-center">
                    <i className="pi pi-check-circle text-4xl text-green-500 mb-2"></i>
                    <div className="text-600 text-sm mb-1">Avancement</div>
                    <div className="text-2xl font-bold">N/A</div>
                  </Card>
                </div>

                <div className="col-12 md:col-3">
                  <Card className="text-center">
                    <i className="pi pi-euro text-4xl text-orange-500 mb-2"></i>
                    <div className="text-600 text-sm mb-1">Budget</div>
                    <div className="text-2xl font-bold">{formatMontant(chantier.montantPrevu || 0)}</div>
                  </Card>
                </div>

                <div className="col-12 md:col-3">
                  <Card className="text-center">
                    <i className="pi pi-users text-4xl text-purple-500 mb-2"></i>
                    <div className="text-600 text-sm mb-1">Équipe</div>
                    <div className="text-2xl font-bold">0</div>
                  </Card>
                </div>
              </div>

              <Divider />

              <div className="grid">
                <div className="col-12">
                  <h3>Accès rapides</h3>
                  <div className="flex flex-wrap gap-2">
                    <Button
                      label="Phases"
                      icon="pi pi-list"
                      onClick={() => router.push(`/chantiers/${id}/phases`)}
                    />
                    <Button
                      label="Budget"
                      icon="pi pi-chart-line"
                      onClick={() => router.push(`/chantiers/${id}/budget`)}
                    />
                    <Button
                      label="Planning"
                      icon="pi pi-calendar"
                      onClick={() => router.push(`/chantiers/${id}/planning`)}
                    />
                    <Button
                      label="Documents"
                      icon="pi pi-file"
                      onClick={() => router.push(`/chantiers/${id}/documents`)}
                    />
                    <Button
                      label="Équipe"
                      icon="pi pi-users"
                      onClick={() => router.push(`/chantiers/${id}/equipe`)}
                    />
                  </div>
                </div>
              </div>
            </TabPanel>

            <TabPanel header="Phases" leftIcon="pi pi-list mr-2">
              <Button
                label="Voir toutes les phases"
                icon="pi pi-arrow-right"
                onClick={() => router.push(`/chantiers/${id}/phases`)}
              />
            </TabPanel>

            <TabPanel header="Budget" leftIcon="pi pi-chart-line mr-2">
              <Button
                label="Voir le budget détaillé"
                icon="pi pi-arrow-right"
                onClick={() => router.push(`/chantiers/${id}/budget`)}
              />
            </TabPanel>

            <TabPanel header="Planning" leftIcon="pi pi-calendar mr-2">
              <Button
                label="Voir le planning complet"
                icon="pi pi-arrow-right"
                onClick={() => router.push(`/chantiers/${id}/planning`)}
              />
            </TabPanel>
          </TabView>
        </Card>
      </div>
    </div>
  );
}
