import { Add, Edit, PowerSettingsNew } from "@mui/icons-material";
import {
  Autocomplete,
  Button,
  Chip,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  IconButton,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useState } from "react";
import styled from "styled-components";
import { esCuentaLegacy, usePlanCuentasQuery } from "../../../tanstack/ContabilidadStack";
import { MonedaInput } from "../../common/MonedaInput";
import {
  useCreateTesCuentaMutation,
  useTesBancosQuery,
  useTesCuentasQuery,
  useToggleTesCuentaMutation,
  useUpdateTesCuentaMutation,
} from "../../../tanstack/TesoreriaStack";

const TIPOS = [
  { value: "BANCO_CC", label: "Cuenta Corriente" },
  { value: "BANCO_CA", label: "Caja de Ahorro" },
  { value: "CAJA_CHICA", label: "Caja Chica" },
  { value: "FONDO_FIJO", label: "Fondo Fijo" },
  { value: "BILLETERA", label: "Billetera Virtual" },
  { value: "MONEDA_EXT", label: "Moneda Extranjera" },
];

const MONEDAS = ["PYG", "USD", "BRL", "EUR", "ARS"];
const TIPO_LABELS = Object.fromEntries(TIPOS.map((t) => [t.value, t.label]));
const TIPO_COLORS = {
  BANCO_CC: "#3b82f6",
  BANCO_CA: "#8b5cf6",
  CAJA_CHICA: "#f59e0b",
  FONDO_FIJO: "#10b981",
  BILLETERA: "#ec4899",
  MONEDA_EXT: "#06b6d4",
};

const esBancaria = (tipo) => tipo === "BANCO_CC" || tipo === "BANCO_CA";

const EMPTY_FORM = {
  nombre: "",
  tipo: "BANCO_CC",
  moneda: "PYG",
  saldo_inicial: 0,
  banco_id: "",
  numero_cuenta: "",
  titular: "",
  saldo_minimo_alerta: 0,
  cuenta_contable_id: "",
};

export const TesCuentasConfigSection = () => {
  const { data: cuentas = [], isLoading } = useTesCuentasQuery();
  const { data: bancos = [] } = useTesBancosQuery();
  const { data: planCuentasRaw = [] } = usePlanCuentasQuery();
  const planCuentas = planCuentasRaw.filter(c => c.acepta_movimientos && !esCuentaLegacy(c));

  const createMut = useCreateTesCuentaMutation();
  const updateMut = useUpdateTesCuentaMutation();
  const toggleMut = useToggleTesCuentaMutation();

  const [modal, setModal] = useState(null);
  const [form, setForm] = useState(EMPTY_FORM);

  const openCreate = () => {
    setForm(EMPTY_FORM);
    setModal({ mode: "create" });
  };

  const openEdit = (cuenta) => {
    setForm({
      nombre: cuenta.nombre || "",
      tipo: cuenta.tipo || "BANCO_CC",
      moneda: cuenta.moneda || "PYG",
      saldo_inicial: Number(cuenta.saldo_inicial) || 0,
      banco_id: cuenta.banco_id || "",
      numero_cuenta: cuenta.numero_cuenta || "",
      titular: cuenta.titular || "",
      saldo_minimo_alerta: Number(cuenta.saldo_minimo_alerta) || 0,
      cuenta_contable_id: cuenta.cuenta_contable_id || "",
    });
    setModal({ mode: "edit", id: cuenta.id });
  };

  const handleSave = async () => {
    const payload = {
      nombre: form.nombre,
      tipo: form.tipo,
      moneda: form.moneda,
      saldo_inicial: form.saldo_inicial,
      banco_id: esBancaria(form.tipo) && form.banco_id ? form.banco_id : undefined,
      numero_cuenta: form.numero_cuenta || undefined,
      titular: form.titular || undefined,
      saldo_minimo_alerta: form.saldo_minimo_alerta || undefined,
      cuenta_contable_id: form.cuenta_contable_id || undefined,
    };
    if (modal.mode === "create") {
      await createMut.mutateAsync(payload);
    } else {
      await updateMut.mutateAsync({ id: modal.id, data: payload });
    }
    setModal(null);
  };

  const isPending = createMut.isPending || updateMut.isPending;

  return (
    <Container>
      <PageHeader>
        <div>
          <Typography variant="h6" fontWeight={600}>Cuentas de Tesorería</Typography>
          <Typography variant="body2" sx={{ opacity: 0.6, mt: 0.5 }}>
            Administrá cuentas bancarias, cajas y billeteras de la empresa.
          </Typography>
        </div>
        <Button variant="contained" startIcon={<Add />} onClick={openCreate}>
          Nueva cuenta
        </Button>
      </PageHeader>

      {isLoading ? (
        <LoadingWrap><CircularProgress size={28} /></LoadingWrap>
      ) : cuentas.length === 0 ? (
        <EmptyWrap>
          <Typography variant="body2" sx={{ opacity: 0.5 }}>
            Aún no hay cuentas configuradas. Creá la primera cuenta para comenzar.
          </Typography>
        </EmptyWrap>
      ) : (
        <Grid>
          {cuentas.map((c) => (
            <CuentaCard key={c.id} $inactivo={!c.activo}>
              <CardTop>
                <TipoBadge style={{ background: TIPO_COLORS[c.tipo] + "22", color: TIPO_COLORS[c.tipo] }}>
                  {TIPO_LABELS[c.tipo] || c.tipo}
                </TipoBadge>
                <CardActions>
                  <Tooltip title="Editar">
                    <IconButton size="small" onClick={() => openEdit(c)}>
                      <Edit fontSize="small" />
                    </IconButton>
                  </Tooltip>
                  <Tooltip title={c.activo ? "Desactivar" : "Activar"}>
                    <IconButton
                      size="small"
                      color={c.activo ? "error" : "success"}
                      onClick={() => toggleMut.mutate(c.id)}
                      disabled={toggleMut.isPending}
                    >
                      <PowerSettingsNew fontSize="small" />
                    </IconButton>
                  </Tooltip>
                </CardActions>
              </CardTop>

              <CuentaNombre $inactivo={!c.activo}>{c.nombre}</CuentaNombre>

              {c.numero_cuenta && (
                <Typography variant="caption" sx={{ opacity: 0.55, fontFamily: "monospace" }}>
                  {c.numero_cuenta}
                </Typography>
              )}

              <SaldoRow>
                <SaldoMonto>
                  {c.moneda} {(c.saldo_actual ?? 0).toLocaleString("es-PY")}
                </SaldoMonto>
                {!c.activo && <Chip label="Inactiva" size="small" sx={{ opacity: 0.6 }} />}
              </SaldoRow>

              {c.saldo_minimo_alerta != null &&
                Number(c.saldo_actual) < Number(c.saldo_minimo_alerta) && (
                  <AlertaMin>⚠ Saldo bajo el mínimo configurado</AlertaMin>
                )}
            </CuentaCard>
          ))}
        </Grid>
      )}

      <Dialog open={!!modal} onClose={() => setModal(null)} maxWidth="sm" fullWidth>
        <DialogTitle>
          {modal?.mode === "create" ? "Nueva cuenta de tesorería" : "Editar cuenta"}
        </DialogTitle>
        <DialogContent>
          <Fields>
            <TextField
              label="Nombre"
              required
              fullWidth
              size="small"
              value={form.nombre}
              onChange={(e) => setForm((f) => ({ ...f, nombre: e.target.value }))}
              helperText='Ej: "BNF Cuenta Corriente Principal"'
            />

            <FieldRow>
              <FormControl fullWidth size="small">
                <InputLabel>Tipo de cuenta</InputLabel>
                <Select
                  value={form.tipo}
                  label="Tipo de cuenta"
                  onChange={(e) => setForm((f) => ({ ...f, tipo: e.target.value }))}
                >
                  {TIPOS.map((t) => (
                    <MenuItem key={t.value} value={t.value}>{t.label}</MenuItem>
                  ))}
                </Select>
              </FormControl>

              <FormControl fullWidth size="small">
                <InputLabel>Moneda</InputLabel>
                <Select
                  value={form.moneda}
                  label="Moneda"
                  onChange={(e) => setForm((f) => ({ ...f, moneda: e.target.value }))}
                >
                  {MONEDAS.map((m) => (
                    <MenuItem key={m} value={m}>{m}</MenuItem>
                  ))}
                </Select>
              </FormControl>
            </FieldRow>

            {esBancaria(form.tipo) && (
              <Autocomplete
                fullWidth
                options={bancos}
                getOptionLabel={(b) => b.descripcion || b.nombre || ""}
                value={bancos.find((b) => b.id === form.banco_id) || null}
                onChange={(_, val) => setForm((f) => ({ ...f, banco_id: val?.id || "" }))}
                renderInput={(params) => <TextField {...params} label="Banco" size="small" />}
                isOptionEqualToValue={(opt, val) => opt.id === val?.id}
                noOptionsText="Sin resultados"
                clearText="Limpiar"
              />
            )}

            <FieldRow>
              <MonedaInput
                label="Saldo inicial"
                fullWidth
                moneda={form.moneda}
                allowNegative
                value={form.saldo_inicial}
                onChange={(v) => setForm((f) => ({ ...f, saldo_inicial: v }))}
                helperText="Solo al crear la cuenta. Puede ser negativo (sobregiro)"
                disabled={modal?.mode === "edit"}
              />
              <MonedaInput
                label="Saldo mínimo de alerta"
                fullWidth
                moneda={form.moneda}
                allowNegative
                value={form.saldo_minimo_alerta}
                onChange={(v) => setForm((f) => ({ ...f, saldo_minimo_alerta: v }))}
                helperText="Alerta cuando el saldo baja de este valor. Puede ser negativo (límite de sobregiro)"
              />
            </FieldRow>

            {esBancaria(form.tipo) && (
              <TextField
                label="Número de cuenta"
                fullWidth
                size="small"
                value={form.numero_cuenta}
                onChange={(e) => setForm((f) => ({ ...f, numero_cuenta: e.target.value }))}
              />
            )}

            <TextField
              label="Titular (si difiere de la empresa)"
              fullWidth
              size="small"
              value={form.titular}
              onChange={(e) => setForm((f) => ({ ...f, titular: e.target.value }))}
            />

            {planCuentas.length > 0 && (
              <Autocomplete
                fullWidth
                options={planCuentas}
                getOptionLabel={(c) => c.codigo ? `${c.codigo} — ${c.descripcion}` : (c.descripcion || "")}
                value={planCuentas.find((c) => c.id === form.cuenta_contable_id) || null}
                onChange={(_, val) => setForm((f) => ({ ...f, cuenta_contable_id: val?.id || "" }))}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    label="Cuenta contable"
                    size="small"
                    helperText="Cuenta del plan contable para asientos automáticos"
                  />
                )}
                isOptionEqualToValue={(opt, val) => opt.id === val?.id}
                noOptionsText="Sin cuentas configuradas"
                clearText="Limpiar"
              />
            )}
          </Fields>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setModal(null)}>Cancelar</Button>
          <Button
            variant="contained"
            onClick={handleSave}
            disabled={isPending || !form.nombre.trim()}
          >
            {isPending ? <CircularProgress size={18} /> : "Guardar"}
          </Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

const Container = styled.div`padding: 24px; height: 100%; overflow-y: auto;`;
const PageHeader = styled.div`display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 24px;`;
const LoadingWrap = styled.div`display: flex; justify-content: center; padding: 48px;`;
const EmptyWrap = styled.div`padding: 48px; text-align: center; border: 1px dashed ${({ theme }) => theme.color2}; border-radius: 12px;`;
const Grid = styled.div`display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 16px;`;
const CuentaCard = styled.div`background: ${({ theme }) => theme.bg2}; border: 1px solid ${({ theme }) => theme.color2}; border-radius: 12px; padding: 16px; display: flex; flex-direction: column; gap: 6px; opacity: ${({ $inactivo }) => $inactivo ? 0.55 : 1}; transition: opacity 0.2s;`;
const CardTop = styled.div`display: flex; justify-content: space-between; align-items: center;`;
const TipoBadge = styled.span`font-size: 11px; font-weight: 600; padding: 2px 10px; border-radius: 20px;`;
const CardActions = styled.div`display: flex; gap: 2px;`;
const CuentaNombre = styled.div`font-size: 15px; font-weight: 600; color: ${({ theme, $inactivo }) => $inactivo ? theme.text2 : theme.text1}; margin-top: 4px;`;
const SaldoRow = styled.div`display: flex; align-items: center; justify-content: space-between; margin-top: 6px;`;
const SaldoMonto = styled.div`font-size: 18px; font-weight: 700; color: ${({ theme }) => theme.primary};`;
const AlertaMin = styled.div`font-size: 11px; color: #f59e0b; margin-top: 2px;`;
const Fields = styled.div`display: flex; flex-direction: column; gap: 16px; margin-top: 8px;`;
const FieldRow = styled.div`display: flex; gap: 12px;`;
