/* eslint-disable react/prop-types */
import { useState } from "react";
import {
  Alert,
  Avatar,
  Box,
  Button,
  Chip,
  Container,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControlLabel,
  FormGroup,
  IconButton,
  MenuItem,
  Paper,
  Skeleton,
  Stack,
  Switch,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tabs,
  Tab,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { Icon } from "@iconify/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Link } from "react-router-dom";
import { toast } from "sonner";
import { EmptyState, ScreenGuia } from "../../components/_standards";
import { fmtFechaHora, fmtFechaCalendario } from "../../utils/fecha";
import { usePermission } from "../../hooks/usePermission";
import { useConfirmDialog } from "../../hooks/useConfirmDialog";
import {
  crearApiKey,
  getApiAudit,
  listarApiKeys,
  revocarApiKey,
} from "../../api/cartera.service";

const ESTADO_COLOR = {
  activa: "success",
  revocada: "error",
  expirada: "warning",
};

const SCOPES = [
  { value: "sync", label: "sync", desc: "Sincronizar cartera (snapshot/delta)" },
  { value: "cobros", label: "cobros", desc: "Notificar cobros externos" },
  { value: "gestiones", label: "gestiones", desc: "Registrar gestiones externas" },
];

const CODE_SAMPLES = {
  sync: `curl -X POST https://tu-erp.com/api/v1/cartera/api/sync \\
  -H "X-Api-Key: sk_carc_XXXX" \\
  -H "Content-Type: application/json" \\
  -d '{
    "modo": "delta",
    "documentos": [{
      "cliente_externo_id": "CLI-001",
      "cliente_nombre": "Pérez SA",
      "cliente_telefono": "0981234567",
      "documento_numero": "FAC-001-2026",
      "monto_total": 1500000,
      "saldo_pendiente": 1500000,
      "fecha_emision": "2026-06-01",
      "fecha_vencimiento": "2026-07-01"
    }]
  }'`,
  cobros: `curl -X POST https://tu-erp.com/api/v1/cartera/api/cobros \\
  -H "X-Api-Key: sk_carc_XXXX" \\
  -H "Content-Type: application/json" \\
  -d '{
    "cliente_externo_id": "CLI-001",
    "documento_numero": "FAC-001-2026",
    "monto": 500000,
    "moneda_codigo": "PYG",
    "fecha": "2026-06-30T10:30:00Z",
    "medio_pago": "TRANSFERENCIA",
    "referencia_externa": "REC-2026-1234"
  }'`,
  gestiones: `curl -X POST https://tu-erp.com/api/v1/cartera/api/gestiones \\
  -H "X-Api-Key: sk_carc_XXXX" \\
  -H "Content-Type: application/json" \\
  -d '{
    "cliente_externo_id": "CLI-001",
    "documento_numero": "FAC-001-2026",
    "tipo_gestion": "LLAMADA",
    "resultado": "PROMESA_PAGO",
    "observacion": "Cliente promete pagar el 5/07",
    "proxima_fecha": "2026-07-05T10:00:00Z"
  }'`,
};

export default function ApiKeysPage() {
  const qc = useQueryClient();
  const { can: canCobranzas } = usePermission("COBRANZAS");
  const canVer = canCobranzas("COB_CART_VER");
  const canConfigurar = canCobranzas("COB_CART_CONFIGURAR");
  const { confirm, dialogs } = useConfirmDialog();
  const [tab, setTab] = useState(0);
  const [crearOpen, setCrearOpen] = useState(false);
  const [nuevaKey, setNuevaKey] = useState(null);

  const { data: keys, isLoading } = useQuery({
    queryKey: ["cartera", "api-keys"],
    queryFn: listarApiKeys,
    enabled: canVer,
  });

  const { data: audit } = useQuery({
    queryKey: ["cartera", "api-audit"],
    queryFn: getApiAudit,
    enabled: canVer && tab === 1,
    refetchInterval: tab === 1 ? 15_000 : false,
  });

  const revocar = useMutation({
    mutationFn: revocarApiKey,
    onSuccess: () => {
      toast.success("API key revocada");
      qc.invalidateQueries({ queryKey: ["cartera", "api-keys"] });
    },
    onError: (err) => toast.error(err?.response?.data?.message ?? "Error al revocar"),
  });

  const handleRevocar = async (k) => {
    const ok = await confirm({
      title: "Revocar API key",
      message: `«${k.nombre}» dejará de funcionar inmediatamente. Esta acción no se puede deshacer. ¿Continuar?`,
      confirmText: "Revocar",
      confirmColor: "error",
    });
    if (ok) revocar.mutate(k.id);
  };

  if (!canVer) {
    return (
      <Container maxWidth="xl" sx={{ py: 3 }}>
        <Typography variant="body2" color="text.secondary">
          No tenés permisos para ver esta sección.
        </Typography>
      </Container>
    );
  }

  return (
    <Container maxWidth="lg" sx={{ py: 3 }}>
      <Stack direction="row" alignItems="center" spacing={1} mb={2}>
        <Button
          component={Link}
          to="/cartera-inteligente"
          startIcon={<Icon icon="lucide:arrow-left" width={16} />}
          size="small"
          variant="text"
          sx={{ minWidth: 0 }}
        >
          Cartera Inteligente
        </Button>
        <Icon icon="lucide:chevron-right" width={14} />
        <Typography variant="body2" color="text.secondary">
          API REST
        </Typography>
      </Stack>

      <Paper
        elevation={0}
        sx={{
          p: 2.5,
          mb: 2,
          borderRadius: 2,
          border: 1,
          borderColor: "divider",
          background: (theme) =>
            theme.palette.mode === "dark"
              ? "linear-gradient(135deg, rgba(20,184,166,0.10) 0%, rgba(20,184,166,0.02) 100%)"
              : "linear-gradient(135deg, rgba(20,184,166,0.08) 0%, rgba(255,255,255,1) 100%)",
        }}
      >
        <Stack direction={{ xs: "column", sm: "row" }} alignItems={{ sm: "center" }} spacing={2}>
          <Avatar variant="rounded" sx={{ width: 48, height: 48, bgcolor: "info.main", boxShadow: 2 }}>
            <Icon icon="lucide:plug" width={26} />
          </Avatar>
          <Box sx={{ flex: 1 }}>
            <Typography variant="h5" fontWeight={700}>
              API REST entrante
            </Typography>
            <Typography variant="body2" color="text.secondary" mt={0.5}>
              Endpoints para que tu sistema externo sincronice cartera y notifique cobros/gestiones.
            </Typography>
          </Box>
          <Button
            variant="contained"
            color="info"
            startIcon={<Icon icon="lucide:key" width={18} />}
            onClick={() => setCrearOpen(true)}
            disabled={!canConfigurar}
            sx={{ minWidth: 180 }}
          >
            Nueva API key
          </Button>
        </Stack>
      </Paper>

      <ScreenGuia titulo="¿Cómo usar la API REST?">
        <Typography variant="body2" component="div">
          1. Generá una API key (botón arriba) — copiala apenas se muestre, no se vuelve a poder ver.
          <br />
          2. Tu sistema manda requests con header <code>X-Api-Key: sk_carc_XXXX</code>.
          <br />
          3. Endpoints disponibles:
          <ul style={{ marginTop: 4, marginBottom: 4 }}>
            <li><code>POST /api/v1/cartera/api/sync</code> — actualizar cartera</li>
            <li><code>POST /api/v1/cartera/api/cobros</code> — notificar cobro</li>
            <li><code>POST /api/v1/cartera/api/gestiones</code> — registrar gestión</li>
          </ul>
          Cada scope se puede limitar individualmente al crear la key.
        </Typography>
      </ScreenGuia>

      <Paper elevation={0} sx={{ mt: 2, borderRadius: 2, border: 1, borderColor: "divider", overflow: "hidden" }}>
        <Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ borderBottom: 1, borderColor: "divider", px: 1 }}>
          <Tab label="Keys" />
          <Tab label="Auditoría" />
          <Tab label="Código de ejemplo" />
        </Tabs>

        {tab === 0 && (
          <Box>
            {isLoading ? (
              <Box sx={{ p: 2 }}>
                <Stack spacing={1}>
                  {[...Array(3)].map((_, i) => (
                    <Skeleton key={i} variant="rounded" height={48} />
                  ))}
                </Stack>
              </Box>
            ) : (keys ?? []).length === 0 ? (
              <Box sx={{ p: 4 }}>
                <EmptyState
                  icon="lucide:key"
                  title="Sin API keys todavía"
                  description="Creá tu primera key para empezar a usar la API REST."
                />
              </Box>
            ) : (
              <TableContainer>
                <Table size="small">
                  <TableHead>
                    <TableRow sx={{ "& th": { fontWeight: 700, bgcolor: "action.hover", textTransform: "uppercase", fontSize: 11, letterSpacing: 0.5, color: "text.secondary" } }}>
                      <TableCell>Nombre</TableCell>
                      <TableCell>Key</TableCell>
                      <TableCell>Scopes</TableCell>
                      <TableCell align="center">Estado</TableCell>
                      <TableCell>Último uso</TableCell>
                      <TableCell>Expira</TableCell>
                      <TableCell align="center">Acciones</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {keys.map((k) => (
                      <TableRow key={k.id} hover>
                        <TableCell>
                          <Typography variant="body2" fontWeight={600}>
                            {k.nombre}
                          </Typography>
                        </TableCell>
                        <TableCell>
                          <Typography variant="caption" sx={{ fontFamily: "monospace" }}>
                            {k.key_prefix}…
                          </Typography>
                        </TableCell>
                        <TableCell>
                          <Stack direction="row" spacing={0.5}>
                            {(k.scopes ?? []).map((s) => (
                              <Chip key={s} size="small" label={s} variant="outlined" sx={{ height: 18, fontSize: 10 }} />
                            ))}
                          </Stack>
                        </TableCell>
                        <TableCell align="center">
                          <Chip size="small" label={k.estado} color={ESTADO_COLOR[k.estado] ?? "default"} sx={{ fontWeight: 600, textTransform: "uppercase", fontSize: 10 }} />
                        </TableCell>
                        <TableCell>
                          <Typography variant="caption">
                            {k.ultimo_uso_at ? fmtFechaHora(k.ultimo_uso_at) : "—"}
                          </Typography>
                        </TableCell>
                        <TableCell>
                          <Typography variant="caption">
                            {k.expira_en ? fmtFechaCalendario(k.expira_en) : "Sin expiración"}
                          </Typography>
                        </TableCell>
                        <TableCell align="center">
                          {k.estado === "activa" && canConfigurar && (
                            <Tooltip title="Revocar" enterDelay={300}>
                              <IconButton size="small" color="error" onClick={() => handleRevocar(k)}>
                                <Icon icon="lucide:trash-2" width={18} />
                              </IconButton>
                            </Tooltip>
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            )}
          </Box>
        )}

        {tab === 1 && (
          <Box>
            {!audit ? (
              <Box sx={{ p: 2 }}>
                <Stack spacing={1}>
                  {[...Array(4)].map((_, i) => (
                    <Skeleton key={i} variant="rounded" height={42} />
                  ))}
                </Stack>
              </Box>
            ) : audit.length === 0 ? (
              <Box sx={{ p: 4 }}>
                <EmptyState
                  icon="lucide:activity"
                  title="Sin actividad"
                  description="No se han recibido llamadas a la API todavía."
                />
              </Box>
            ) : (
              <TableContainer sx={{ maxHeight: 500 }}>
                <Table size="small" stickyHeader>
                  <TableHead>
                    <TableRow sx={{ "& th": { fontWeight: 700, bgcolor: "action.hover", textTransform: "uppercase", fontSize: 11 } }}>
                      <TableCell>Fecha</TableCell>
                      <TableCell>Method</TableCell>
                      <TableCell>Endpoint</TableCell>
                      <TableCell>Key</TableCell>
                      <TableCell align="center">Status</TableCell>
                      <TableCell align="right">Latency</TableCell>
                      <TableCell>Error</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {audit.map((a) => (
                      <TableRow key={a.id} hover>
                        <TableCell>
                          <Typography variant="caption">{fmtFechaHora(a.created_at)}</Typography>
                        </TableCell>
                        <TableCell>
                          <Chip size="small" label={a.method} variant="outlined" sx={{ height: 18, fontSize: 10 }} />
                        </TableCell>
                        <TableCell>
                          <Typography variant="caption" sx={{ fontFamily: "monospace" }}>{a.endpoint}</Typography>
                        </TableCell>
                        <TableCell>
                          <Typography variant="caption">{a.api_key?.nombre ?? "—"}</Typography>
                        </TableCell>
                        <TableCell align="center">
                          <Chip
                            size="small"
                            label={a.status_code}
                            color={a.status_code < 300 ? "success" : a.status_code < 500 ? "warning" : "error"}
                            sx={{ fontWeight: 600, height: 20, fontSize: 10 }}
                          />
                        </TableCell>
                        <TableCell align="right">
                          <Typography variant="caption">{a.latency_ms ?? "—"}ms</Typography>
                        </TableCell>
                        <TableCell>
                          {a.error && (
                            <Tooltip title={a.error}>
                              <Typography
                                variant="caption"
                                color="error.main"
                                sx={{ display: "block", maxWidth: 240, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}
                              >
                                {a.error}
                              </Typography>
                            </Tooltip>
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            )}
          </Box>
        )}

        {tab === 2 && (
          <Box sx={{ p: 2 }}>
            <Typography variant="caption" color="text.secondary" sx={{ display: "block", mb: 2 }}>
              Reemplazá <code>sk_carc_XXXX</code> con tu API key real. Las dependencias son curl/httpie/cualquier cliente HTTP.
            </Typography>
            {Object.entries(CODE_SAMPLES).map(([endpoint, code]) => (
              <Box key={endpoint} sx={{ mb: 2 }}>
                <Typography variant="subtitle2" fontWeight={700} sx={{ textTransform: "uppercase", mb: 1 }}>
                  POST /api/v1/cartera/api/{endpoint}
                </Typography>
                <Paper
                  variant="outlined"
                  sx={{
                    p: 1.5,
                    bgcolor: (theme) => (theme.palette.mode === "dark" ? "grey.900" : "grey.50"),
                    position: "relative",
                  }}
                >
                  <IconButton
                    size="small"
                    onClick={() => {
                      navigator.clipboard.writeText(code);
                      toast.success("Copiado");
                    }}
                    sx={{ position: "absolute", top: 4, right: 4 }}
                  >
                    <Icon icon="lucide:copy" width={14} />
                  </IconButton>
                  <Box
                    component="pre"
                    sx={{
                      m: 0,
                      fontSize: 11,
                      fontFamily: "monospace",
                      whiteSpace: "pre-wrap",
                      pr: 4,
                    }}
                  >
                    {code}
                  </Box>
                </Paper>
              </Box>
            ))}
          </Box>
        )}
      </Paper>

      <CrearKeyDialog
        open={crearOpen}
        onClose={() => setCrearOpen(false)}
        onCreated={(k) => {
          setCrearOpen(false);
          setNuevaKey(k);
          qc.invalidateQueries({ queryKey: ["cartera", "api-keys"] });
        }}
      />
      <KeyPlaintextDialog
        open={!!nuevaKey}
        keyData={nuevaKey}
        onClose={() => setNuevaKey(null)}
      />
      {dialogs}
    </Container>
  );
}

function CrearKeyDialog({ open, onClose, onCreated }) {
  const [form, setForm] = useState({
    nombre: "",
    scopes: ["sync", "cobros", "gestiones"],
    expira_en_dias: "365",
  });

  const crear = useMutation({
    mutationFn: () =>
      crearApiKey({
        nombre: form.nombre.trim(),
        scopes: form.scopes,
        expira_en_dias: form.expira_en_dias ? Number(form.expira_en_dias) : undefined,
      }),
    onSuccess: (data) => {
      onCreated(data);
      setForm({ nombre: "", scopes: ["sync", "cobros", "gestiones"], expira_en_dias: "365" });
    },
    onError: (err) => toast.error(err?.response?.data?.message ?? "Error al crear"),
  });

  const toggleScope = (s) => {
    setForm((f) => ({
      ...f,
      scopes: f.scopes.includes(s) ? f.scopes.filter((x) => x !== s) : [...f.scopes, s],
    }));
  };

  return (
    <Dialog open={open} onClose={onClose} fullWidth maxWidth="sm">
      <DialogTitle>Nueva API key</DialogTitle>
      <DialogContent dividers>
        <Stack spacing={2}>
          <TextField
            label="Nombre de la key"
            value={form.nombre}
            onChange={(e) => setForm((f) => ({ ...f, nombre: e.target.value }))}
            size="small"
            placeholder="Integración FITBANK producción"
            helperText="Etiqueta para identificarla luego"
            fullWidth
          />
          <Box>
            <Typography variant="caption" color="text.secondary" fontWeight={700} sx={{ textTransform: "uppercase", display: "block", mb: 1 }}>
              Scopes
            </Typography>
            <FormGroup>
              {SCOPES.map((s) => (
                <FormControlLabel
                  key={s.value}
                  control={
                    <Switch
                      checked={form.scopes.includes(s.value)}
                      onChange={() => toggleScope(s.value)}
                    />
                  }
                  label={
                    <Box>
                      <Typography variant="body2" fontWeight={600}>
                        {s.label}
                      </Typography>
                      <Typography variant="caption" color="text.secondary">
                        {s.desc}
                      </Typography>
                    </Box>
                  }
                  sx={{ alignItems: "flex-start", m: 0 }}
                />
              ))}
            </FormGroup>
          </Box>
          <TextField
            select
            size="small"
            label="Expira en"
            value={form.expira_en_dias}
            onChange={(e) => setForm((f) => ({ ...f, expira_en_dias: e.target.value }))}
          >
            <MenuItem value="">Sin expiración</MenuItem>
            <MenuItem value="30">30 días</MenuItem>
            <MenuItem value="90">90 días</MenuItem>
            <MenuItem value="180">180 días</MenuItem>
            <MenuItem value="365">1 año</MenuItem>
            <MenuItem value="730">2 años</MenuItem>
          </TextField>
        </Stack>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} disabled={crear.isPending}>
          Cancelar
        </Button>
        <Button
          variant="contained"
          onClick={() => crear.mutate()}
          disabled={crear.isPending || form.nombre.trim().length < 3 || form.scopes.length === 0}
          startIcon={<Icon icon="lucide:key" width={16} />}
        >
          {crear.isPending ? "Creando…" : "Crear key"}
        </Button>
      </DialogActions>
    </Dialog>
  );
}

function KeyPlaintextDialog({ open, keyData, onClose }) {
  if (!keyData) return null;
  return (
    <Dialog open={open} onClose={onClose} fullWidth maxWidth="sm">
      <DialogTitle>
        <Stack direction="row" alignItems="center" spacing={1}>
          <Icon icon="lucide:check-circle" width={22} color="green" />
          <span>API key creada</span>
        </Stack>
      </DialogTitle>
      <DialogContent dividers>
        <Stack spacing={2}>
          <Alert severity="warning" icon={<Icon icon="lucide:triangle-alert" width={20} />}>
            <strong>Esta es la única vez que vas a ver la key.</strong> Copiala ahora — después solo se mostrará el prefijo.
          </Alert>
          <Box>
            <Typography variant="caption" color="text.secondary" fontWeight={700} sx={{ textTransform: "uppercase", display: "block", mb: 1 }}>
              Key — {keyData.nombre}
            </Typography>
            <Paper
              variant="outlined"
              sx={{
                p: 1.5,
                position: "relative",
                bgcolor: (theme) => (theme.palette.mode === "dark" ? "grey.900" : "grey.50"),
              }}
            >
              <Typography
                variant="body2"
                sx={{
                  fontFamily: "monospace",
                  wordBreak: "break-all",
                  pr: 4,
                }}
              >
                {keyData.key_plaintext}
              </Typography>
              <IconButton
                size="small"
                onClick={() => {
                  navigator.clipboard.writeText(keyData.key_plaintext);
                  toast.success("Copiado al portapapeles");
                }}
                sx={{ position: "absolute", top: 4, right: 4 }}
              >
                <Icon icon="lucide:copy" width={16} />
              </IconButton>
            </Paper>
          </Box>
          <Typography variant="caption" color="text.secondary">
            Usá esta key en el header <code>X-Api-Key</code> en todas las requests a la API REST de Cartera Inteligente.
          </Typography>
        </Stack>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} variant="contained">
          Listo, ya la copié
        </Button>
      </DialogActions>
    </Dialog>
  );
}
