"use client"

import { useState } from "react"
import { FirmarHeader } from "@/components/firmar/FirmarHeader"
import { FileUploadSection } from "@/components/firmar/FileUploadSection"
import { SignActions } from "@/components/firmar/SignActions"
import { XmlGenerationDialog } from "@/components/factura/XmlGenerationDialog"
import { useXmlSigning } from "@/hooks/firmar/useXmlSigning"

export default function FirmarPage() {
  const [dialogOpen, setDialogOpen] = useState(false)

  const {
    xmlFile,
    p12File,
    password,
    isLoading,
    signedXml,
    setXmlFile,
    setP12File,
    setPassword,
    handleSign,
    handleDownload,
    handleReset,
  } = useXmlSigning()

  const handleSignClick = async () => {
    const success = await handleSign()
    if (success) {
      setDialogOpen(true)
    }
  }

  return (
    <div className="container mx-auto max-w-4xl py-8 space-y-8">
      <FirmarHeader />

      <FileUploadSection
        xmlFile={xmlFile}
        p12File={p12File}
        password={password}
        isLoading={isLoading}
        onXmlFileChange={setXmlFile}
        onP12FileChange={setP12File}
        onPasswordChange={setPassword}
      />

      <SignActions
        xmlFile={xmlFile}
        p12File={p12File}
        password={password}
        isLoading={isLoading}
        onSign={handleSignClick}
      />

      {/* Modal de XML Firmado */}
      <XmlGenerationDialog
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        xmlGenerado={signedXml || ""}
        onDescargarXml={handleDownload}
      />
    </div>
  )
}
