'use client';

import { useEffect, useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { FielUploadModal } from '@/components/sat/FielUploadModal';
import { SyncStatus } from '@/components/sat/SyncStatus';
import { SyncHistory } from '@/components/sat/SyncHistory';
import { getFielStatus, deleteFiel } from '@/lib/api/fiel';
import type { FielStatus } from '@horux/shared';

export default function SatConfigPage() {
  const [fielStatus, setFielStatus] = useState<FielStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [showUploadModal, setShowUploadModal] = useState(false);
  const [deleting, setDeleting] = useState(false);

  const fetchFielStatus = async () => {
    try {
      const status = await getFielStatus();
      setFielStatus(status);
    } catch (err) {
      console.error('Error fetching FIEL status:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchFielStatus();
  }, []);

  const handleUploadSuccess = (status: FielStatus) => {
    setFielStatus(status);
    setShowUploadModal(false);
  };

  const handleDelete = async () => {
    if (!confirm('Estas seguro de eliminar la FIEL? Se detendran las sincronizaciones automaticas.')) {
      return;
    }

    setDeleting(true);
    try {
      await deleteFiel();
      setFielStatus({ configured: false });
    } catch (err) {
      console.error('Error deleting FIEL:', err);
    } finally {
      setDeleting(false);
    }
  };

  if (loading) {
    return (
      <div className="p-6">
        <h1 className="text-2xl font-bold mb-6">Configuracion SAT</h1>
        <p>Cargando...</p>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold">Configuracion SAT</h1>
          <p className="text-muted-foreground">
            Gestiona tu FIEL y la sincronizacion automatica de CFDIs
          </p>
        </div>
      </div>

      {/* Estado de la FIEL */}
      <Card>
        <CardHeader>
          <CardTitle>FIEL (e.firma)</CardTitle>
          <CardDescription>
            Tu firma electronica para autenticarte con el SAT
          </CardDescription>
        </CardHeader>
        <CardContent>
          {fielStatus?.configured ? (
            <div className="space-y-4">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div>
                  <p className="text-sm text-muted-foreground">RFC</p>
                  <p className="font-medium">{fielStatus.rfc}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">No. Serie</p>
                  <p className="font-medium text-xs">{fielStatus.serialNumber}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Vigente hasta</p>
                  <p className="font-medium">
                    {fielStatus.validUntil ? new Date(fielStatus.validUntil).toLocaleDateString('es-MX') : '-'}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Estado</p>
                  <p className={`font-medium ${fielStatus.isExpired ? 'text-red-500' : 'text-green-500'}`}>
                    {fielStatus.isExpired ? 'Vencida' : `Valida (${fielStatus.daysUntilExpiration} dias)`}
                  </p>
                </div>
              </div>

              <div className="flex gap-3">
                <Button
                  variant="outline"
                  onClick={() => setShowUploadModal(true)}
                >
                  Actualizar FIEL
                </Button>
                <Button
                  variant="destructive"
                  onClick={handleDelete}
                  disabled={deleting}
                >
                  {deleting ? 'Eliminando...' : 'Eliminar FIEL'}
                </Button>
              </div>
            </div>
          ) : (
            <div className="space-y-4">
              <p className="text-muted-foreground">
                No tienes una FIEL configurada. Sube tu certificado y llave privada para habilitar
                la sincronizacion automatica de CFDIs con el SAT.
              </p>
              <Button onClick={() => setShowUploadModal(true)}>
                Configurar FIEL
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Estado de Sincronizacion */}
      <SyncStatus
        fielConfigured={fielStatus?.configured || false}
        onSyncStarted={fetchFielStatus}
      />

      {/* Historial */}
      <SyncHistory fielConfigured={fielStatus?.configured || false} />

      {/* Modal de carga */}
      {showUploadModal && (
        <FielUploadModal
          onSuccess={handleUploadSuccess}
          onClose={() => setShowUploadModal(false)}
        />
      )}
    </div>
  );
}
