"use client";

import { useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import { AlertTriangle } from "lucide-react";
import { usePageTitle } from "@/hooks/usePageTitle";

export default function ContractViewerContent() {
  const searchParams = useSearchParams();
  const contractId = searchParams.get("contract_id");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [presignedUrl, setPresignedUrl] = useState<string | null>(null);
  const [contractNumber, setContractNumber] = useState<string | null>(null);

  // Définir le titre de la page
  usePageTitle(contractNumber ? `Contrat ${contractNumber}` : "Contrat de travail signé");

  useEffect(() => {
    if (!contractId) {
      setError("Aucun identifiant de contrat fourni");
      setLoading(false);
      return;
    }

    const fetchPresignedUrl = async () => {
      try {
        const response = await fetch(`/api/dl-contrat-signe?contract_id=${encodeURIComponent(contractId)}`);
        const data = await response.json();

        if (!response.ok) {
          throw new Error(data.error || "Erreur lors de la récupération du contrat");
        }

        if (data.body && data.body.presignedUrl) {
          setPresignedUrl(data.body.presignedUrl);
          if (data.body.contractNumber) {
            setContractNumber(data.body.contractNumber);
          }
        } else {
          throw new Error("URL présignée non récupérée");
        }
      } catch (err) {
        console.error("Erreur lors de la récupération de l'URL présignée:", err);
        setError(err instanceof Error ? err.message : "Erreur inconnue");
      } finally {
        setLoading(false);
      }
    };

    fetchPresignedUrl();
  }, [contractId]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <div className="text-gray-600">Chargement du contrat...</div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="max-w-md mx-auto text-center p-6 bg-white rounded-lg shadow-lg">
          <div className="text-red-600 mb-4">
            <AlertTriangle className="w-12 h-12 mx-auto" />
          </div>
          <h1 className="text-xl font-semibold text-gray-900 mb-2">Erreur</h1>
          <p className="text-gray-600 mb-4">{error}</p>
          <button 
            onClick={() => window.location.reload()} 
            className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition-colors"
          >
            Réessayer
          </button>
        </div>
      </div>
    );
  }

  if (!presignedUrl) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="max-w-md mx-auto text-center p-6 bg-white rounded-lg shadow-lg">
          <h1 className="text-xl font-semibold text-gray-900 mb-2">Contrat non disponible</h1>
          <p className="text-gray-600">Le contrat demandé n'est pas disponible ou n'existe pas.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="h-screen flex flex-col">
      {/* Header simple */}
      <div className="bg-white border-b border-gray-200 px-6 py-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <img 
              src="https://ci3.googleusercontent.com/meips/ADKq_NaYk41Pm5XLYFH2kxxXdCOkuRa2Ji2vLeI41LRtc9oBmfS7-NhGtPUzYhw7arh9LdEyrUS--rk3mW1WSrKTtKjsTtiUcZVwfYFyqvV8YSZ8ZFJtQzqG43CgPmcZsSdWmIrxmPATULmFaFEpIIO-IdbHkat3RBeqwDQ=s0-d-e1-ft#https://newstaging.odentas.fr/wp-content/uploads/2025/08/Odentas-Logo-Bleu-Fond-Transparent-4-1.png" 
              alt="Odentas" 
              className="h-8"
            />
            <h1 className="text-lg font-semibold text-gray-900">Contrat de travail signé</h1>
          </div>
          <a 
            href={presignedUrl} 
            download 
            className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition-colors text-sm font-medium"
          >
            Télécharger
          </a>
        </div>
      </div>

      {/* Viewer iframe */}
      <div className="flex-1 bg-gray-50">
        <iframe
          id="pdf-viewer"
          src={presignedUrl}
          className="w-full h-full border-0"
          title="Contrat de travail signé"
        />
      </div>
    </div>
  );
}