'use client';

import { useEffect, useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, Button } from '@horux/shared-ui';
import { FielUploadModal } from '@/components/sat/FielUploadModal';
import { SyncStatus } from '@/components/sat/SyncStatus';
import { SyncHistory } from '@/components/sat/SyncHistory';
import { Header } from '@/components/layouts/header';
import { getFielStatus, deleteFiel } from '@/lib/api/fiel';
import { useTenantViewStore } from '@/stores/tenant-view-store';
import { useContribuyenteStore } from '@/stores/contribuyente-store';
import { useAuthStore } from '@/stores/auth-store';

import { Building2 } from 'lucide-react';
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 { viewingTenantId } = useTenantViewStore();
  const { selectedContribuyenteId, selectedContribuyenteRfc, selectedContribuyenteNombre } = useContribuyenteStore();

  // Per-contribuyente FIEL when a contribuyente is selected; otherwise tenant-level legacy
  const contribId = selectedContribuyenteId || null;

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

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

  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(contribId);
      setFielStatus({ configured: false });
    } catch (err) {
      console.error('Error deleting FIEL:', err);
    } finally {
      setDeleting(false);
    }
  };

  if (loading) {
    return (
      <>
        <Header title="Configuración SAT" />
        <div className="p-6">
          <p>Cargando...</p>
        </div>
      </>
    );
  }

  return (
    <>
      <Header title="Configuración SAT" />
      <main className="p-6 space-y-6">

      {/* Show which contribuyente or prompt to select */}
      {!selectedContribuyenteId && (
        <Card className="border-amber-200 bg-amber-50 dark:bg-amber-950/20">
          <CardContent className="py-4 flex items-center gap-3">
            <Building2 className="h-5 w-5 text-amber-600" />
            <p className="text-sm text-amber-800 dark:text-amber-300">Selecciona un contribuyente en el header para ver y configurar su FIEL.</p>
          </CardContent>
        </Card>
      )}

      {selectedContribuyenteId && (
        <Card className="bg-primary/5 border-primary/20">
          <CardContent className="py-3 px-5 flex items-center gap-2">
            <Building2 className="h-4 w-4 text-primary" />
            <span className="text-sm font-medium">FIEL de: {selectedContribuyenteNombre}</span>
            <span className="text-xs text-muted-foreground font-mono">{selectedContribuyenteRfc}</span>
          </CardContent>
        </Card>
      )}

      {/* Hide FIEL UI when no contribuyente is selected */}
      {!selectedContribuyenteId ? null : (
      <>
      {/* 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}
        contribuyenteId={contribId}
      />

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

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