import { Icon } from "@iconify/react";
import { Dialog, DialogActions, DialogContent, DialogTitle, Switch, TextField, Button, Tooltip } from "@mui/material";
import { useState } from "react";
import styled from "styled-components";
import { usePermission } from "../../hooks/usePermission";
import {
  useCentrosCostoQuery,
  useCrearCentroCostoMutation,
  useEditarCentroCostoMutation,
  useEliminarCentroCostoMutation,
} from "../../tanstack/ContabilidadStack";

const EMPTY_FORM = { codigo: "", descripcion: "" };

export function CentrosCostoTab() {
  const { can } = usePermission("CONTABILIDAD");
  const canCreate = can("CONT_CC_CENTRO_COSTO_CREAR");
  const canEdit = can("CONT_CC_CENTRO_COSTO_EDITAR");
  const canDelete = can("CONT_CC_CENTRO_COSTO_ELIMINAR");

  const { data: centros = [], isLoading } = useCentrosCostoQuery();
  const crearMutation = useCrearCentroCostoMutation();
  const editarMutation = useEditarCentroCostoMutation();
  const eliminarMutation = useEliminarCentroCostoMutation();

  const [dialog, setDialog] = useState(null); // null | { mode: 'crear'|'editar', data }
  const [form, setForm] = useState(EMPTY_FORM);
  const [deleteConfirm, setDeleteConfirm] = useState(null);

  const openCrear = () => {
    setForm(EMPTY_FORM);
    setDialog({ mode: "crear" });
  };

  const openEditar = (c) => {
    setForm({ codigo: c.codigo, descripcion: c.descripcion });
    setDialog({ mode: "editar", data: c });
  };

  const handleGuardar = () => {
    if (dialog.mode === "crear") {
      crearMutation.mutate(form, { onSuccess: () => setDialog(null) });
    } else {
      editarMutation.mutate(
        { id: dialog.data.id, data: { descripcion: form.descripcion } },
        { onSuccess: () => setDialog(null) },
      );
    }
  };

  const handleToggleActivo = (c) => {
    editarMutation.mutate({ id: c.id, data: { activo: !c.activo } });
  };

  const handleEliminar = () => {
    eliminarMutation.mutate(deleteConfirm.id, { onSuccess: () => setDeleteConfirm(null) });
  };

  const isPending = crearMutation.isPending || editarMutation.isPending;

  if (isLoading) {
    return (
      <LoadingWrap>
        <Icon icon="lucide:loader-circle" style={{ animation: "spin 1s linear infinite" }} />
        Cargando centros de costo...
        <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
      </LoadingWrap>
    );
  }

  return (
    <Wrapper>
      <TopBar>
        <TitleBlock>
          <Icon icon="lucide:building-2" />
          <div>
            <h2>Centros de Costo</h2>
            <p>Agrupá asientos contables por área, proyecto o departamento.</p>
          </div>
        </TitleBlock>
        {canCreate && (
          <AddBtn onClick={openCrear}>
            <Icon icon="lucide:plus" />
            Nuevo centro
          </AddBtn>
        )}
      </TopBar>

      {centros.length === 0 ? (
        <EmptyState>
          <Icon icon="lucide:building-2" />
          <strong>Sin centros de costo</strong>
          <p>Creá el primero para poder asignar asientos por área o proyecto.</p>
          {canCreate && (
            <AddBtn onClick={openCrear}><Icon icon="lucide:plus" /> Nuevo centro</AddBtn>
          )}
        </EmptyState>
      ) : (
        <Table>
          <thead>
            <tr>
              <Th>Código</Th>
              <Th>Descripción</Th>
              <Th align="center">Activo</Th>
              {(canEdit || canDelete) && <Th align="right">Acciones</Th>}
            </tr>
          </thead>
          <tbody>
            {centros.map((c) => (
              <tr key={c.id}>
                <Td><Code>{c.codigo}</Code></Td>
                <Td>{c.descripcion}</Td>
                <Td align="center">
                  {canEdit ? (
                    <Switch
                      size="small"
                      checked={!!c.activo}
                      onChange={() => handleToggleActivo(c)}
                      disabled={editarMutation.isPending}
                      sx={{ "& .MuiSwitch-switchBase.Mui-checked": { color: "#f88533" }, "& .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track": { backgroundColor: "#f88533" } }}
                    />
                  ) : (
                    <ActiveDot $ok={c.activo} />
                  )}
                </Td>
                {(canEdit || canDelete) && (
                  <Td align="right">
                    <Actions>
                      {canEdit && (
                        <Tooltip title="Editar">
                          <IconBtn onClick={() => openEditar(c)}>
                            <Icon icon="lucide:pencil" />
                          </IconBtn>
                        </Tooltip>
                      )}
                      {canDelete && (
                        <Tooltip title="Eliminar">
                          <IconBtn $red onClick={() => setDeleteConfirm(c)}>
                            <Icon icon="lucide:trash-2" />
                          </IconBtn>
                        </Tooltip>
                      )}
                    </Actions>
                  </Td>
                )}
              </tr>
            ))}
          </tbody>
        </Table>
      )}

      {/* Dialog crear/editar */}
      <Dialog open={!!dialog} onClose={() => setDialog(null)} maxWidth="xs" fullWidth>
        <DialogTitle>{dialog?.mode === "crear" ? "Nuevo Centro de Costo" : "Editar Centro de Costo"}</DialogTitle>
        <DialogContent sx={{ display: "flex", flexDirection: "column", gap: 2.5, pt: "16px !important" }}>
          <TextField
            label="Código"
            size="small"
            value={form.codigo}
            onChange={(e) => setForm((p) => ({ ...p, codigo: e.target.value.toUpperCase() }))}
            disabled={dialog?.mode === "editar"}
            placeholder="Ej: ADMIN, VENTAS, PROYECTO-A"
            inputProps={{ maxLength: 20 }}
          />
          <TextField
            label="Descripción"
            size="small"
            value={form.descripcion}
            onChange={(e) => setForm((p) => ({ ...p, descripcion: e.target.value }))}
            placeholder="Ej: Administración General"
          />
        </DialogContent>
        <DialogActions sx={{ p: 2, gap: 1 }}>
          <Button onClick={() => setDialog(null)}>Cancelar</Button>
          <Button
            variant="contained"
            disabled={!form.codigo || !form.descripcion || isPending}
            onClick={handleGuardar}
            sx={{ background: "#f88533", "&:hover": { background: "#e07320" } }}
          >
            {isPending ? "Guardando…" : "Guardar"}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Dialog confirmar eliminación */}
      <Dialog open={!!deleteConfirm} onClose={() => setDeleteConfirm(null)} maxWidth="xs" fullWidth>
        <DialogTitle>¿Eliminar centro de costo?</DialogTitle>
        <DialogContent>
          <p style={{ margin: 0, fontSize: 14, lineHeight: 1.6 }}>
            Vas a eliminar <strong>{deleteConfirm?.codigo} — {deleteConfirm?.descripcion}</strong>.<br />
            Esto solo es posible si no tiene asientos asignados.
          </p>
        </DialogContent>
        <DialogActions sx={{ p: 2, gap: 1 }}>
          <Button onClick={() => setDeleteConfirm(null)}>Cancelar</Button>
          <Button
            variant="contained"
            color="error"
            disabled={eliminarMutation.isPending}
            onClick={handleEliminar}
          >
            {eliminarMutation.isPending ? "Eliminando…" : "Eliminar"}
          </Button>
        </DialogActions>
      </Dialog>

      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </Wrapper>
  );
}

// ── Styles ────────────────────────────────────────────────────────────────────
const Wrapper = styled.div`position: relative;`;

const TopBar = styled.div`
  display: flex; align-items: flex-start; justify-content: space-between;
  gap: 16px; margin-bottom: 24px; flex-wrap: wrap;
`;
const TitleBlock = styled.div`
  display: flex; align-items: flex-start; gap: 12px;
  > svg { width: 24px; height: 24px; color: #f88533; flex-shrink: 0; margin-top: 2px; }
  h2 { margin: 0 0 4px; font-size: 16px; font-weight: 700; color: ${({ theme }) => theme.text}; }
  p  { margin: 0; font-size: 13px; color: ${({ theme }) => theme.text}88; }
`;
const AddBtn = styled.button`
  display: flex; align-items: center; gap: 7px;
  padding: 9px 18px; background: #f88533; color: #fff;
  border: none; border-radius: 8px; font-size: 13px; font-weight: 600;
  cursor: pointer; white-space: nowrap; transition: background 0.15s;
  &:hover { background: #e0742a; }
  svg { width: 16px; height: 16px; }
`;

const Table = styled.table`
  width: 100%; border-collapse: collapse; font-size: 13px;
  background: ${({ theme }) => theme.bg2};
  border: 1px solid ${({ theme }) => theme.color2};
  border-radius: 10px; overflow: hidden;
`;
const Th = styled.th`
  padding: 11px 16px; text-align: ${({ align }) => align || "left"};
  font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px;
  color: ${({ theme }) => theme.text}88; background: ${({ theme }) => theme.bg3};
  border-bottom: 1px solid ${({ theme }) => theme.color2};
`;
const Td = styled.td`
  padding: 12px 16px; text-align: ${({ align }) => align || "left"};
  color: ${({ theme }) => theme.text};
  border-bottom: 1px solid ${({ theme }) => theme.color2}50;
  tr:last-child & { border-bottom: none; }
`;
const Code = styled.span`
  font-family: monospace; font-size: 12px; font-weight: 700;
  background: ${({ theme }) => theme.bg3}; padding: 2px 8px;
  border-radius: 5px; color: #f88533;
`;
const ActiveDot = styled.span`
  display: inline-block; width: 8px; height: 8px; border-radius: 50%;
  background: ${({ $ok }) => $ok ? "#22c55e" : "#e2e8f0"};
  border: 1.5px solid ${({ $ok }) => $ok ? "#16a34a" : "#cbd5e1"};
`;
const Actions = styled.div`display: flex; align-items: center; justify-content: flex-end; gap: 6px;`;
const IconBtn = styled.button`
  width: 30px; height: 30px; display: flex; align-items: center; justify-content: center;
  border: 1px solid ${({ $red }) => $red ? "#ef444440" : "transparent"};
  border-radius: 7px; background: transparent; cursor: pointer;
  color: ${({ $red, theme }) => $red ? "#ef4444" : theme.text + "66"};
  transition: background 0.12s;
  &:hover { background: ${({ $red }) => $red ? "#ef444418" : "#00000010"}; }
  svg { width: 14px; height: 14px; }
`;

const EmptyState = styled.div`
  display: flex; flex-direction: column; align-items: center;
  gap: 10px; padding: 60px 20px; text-align: center;
  color: ${({ theme }) => theme.text}88;
  svg { width: 40px; height: 40px; opacity: 0.3; }
  strong { font-size: 15px; color: ${({ theme }) => theme.text}; }
  p { font-size: 13px; margin: 0; }
`;
const LoadingWrap = styled.div`
  display: flex; align-items: center; justify-content: center;
  gap: 10px; padding: 60px; color: ${({ theme }) => theme.text}88; font-size: 14px;
  svg { width: 20px; height: 20px; }
`;
