import { Icon } from "@iconify/react";
import { Box, Tab, Tabs } from "@mui/material";
import { useRef } from "react";
import { useSearchParams } from "react-router-dom";
import styled from "styled-components";
import { AsientosTab } from "../components/contabilidad/AsientosTab";
import { EjerciciosTab } from "../components/contabilidad/EjerciciosTab";
import { PlanCuentasTab } from "../components/contabilidad/PlanCuentasTab";
import { ReportesContablesTab } from "../components/contabilidad/ReportesContablesTab";
import { MapeoCuentasTab } from "../components/contabilidad/MapeoCuentasTab";
import { CentrosCostoTab } from "../components/contabilidad/CentrosCostoTab";
import { TipoCambioTab } from "../components/contabilidad/TipoCambioTab";
import { ConciliacionContablePage } from "./ConciliacionContablePage";
import { SetupBanner } from "../components/contabilidad/SetupBanner";
import { usePeriodoActivoQuery, usePlanCuentasQuery, useSeedPlanCuentasMutation } from "../tanstack/ContabilidadStack";

const TABS = [
  { key: "asientos", label: "Asientos", icon: "lucide:book-open-text" },
  { key: "reportes", label: "Reportes", icon: "lucide:chart-bar" },
  { key: "conciliacion", label: "Conciliación", icon: "lucide:refresh-cw" },
  { key: "plan", label: "Plan de Cuentas", icon: "lucide:list-tree" },
  { key: "ejercicios", label: "Ejercicios", icon: "lucide:calendar-range" },
  { key: "mapeo", label: "Mapeo de Cuentas", icon: "lucide:git-merge" },
  { key: "centros-costo", label: "Centros de Costo", icon: "lucide:building-2" },
  { key: "tipo-cambio", label: "Tipo de Cambio", icon: "lucide:coins" },
];

function TabPanel({ children, value, index }) {
  return (
    <div role="tabpanel" hidden={value !== index}>
      {value === index && <Box sx={{ pt: 2 }}>{children}</Box>}
    </div>
  );
}

export function Contabilidad() {
  const [searchParams, setSearchParams] = useSearchParams();
  const tab = Math.max(0, TABS.findIndex((t) => t.key === (searchParams.get("tab") ?? "asientos")));
  const setTab = (idx) => setSearchParams({ tab: TABS[idx]?.key ?? "asientos" }, { replace: true });
  const { data: planCuentas } = usePlanCuentasQuery();
  const { data: periodoActivo } = usePeriodoActivoQuery();
  const seedMutation = useSeedPlanCuentasMutation();
  const crearEjRef = useRef(null);

  const handleCrearEjercicio = () => {
    setTab(3); // ir a tab Ejercicios
    setTimeout(() => crearEjRef.current?.(), 150);
  };

  return (
    <PageWrapper>
      <PageHeader>
        <HeaderLeft>
          <PageIcon>
            <Icon icon="lucide:landmark" />
          </PageIcon>
          <div>
            <PageTitle>Contabilidad</PageTitle>
            <PageSubtitle>Asientos, plan de cuentas, ejercicios y reportes financieros</PageSubtitle>
          </div>
        </HeaderLeft>
        <StatusBadges>
          <StatusPill $ok={!!periodoActivo?.periodoId}>
            <Icon icon={periodoActivo?.periodoId ? "lucide:check-circle-2" : "lucide:circle-dashed"} />
            {periodoActivo?.periodoId ? "Período abierto" : "Sin período activo"}
          </StatusPill>
          <StatusPill $ok={(planCuentas?.length || 0) > 0}>
            <Icon icon={(planCuentas?.length || 0) > 0 ? "lucide:check-circle-2" : "lucide:circle-dashed"} />
            {(planCuentas?.length || 0) > 0 ? `${planCuentas.length} cuentas` : "Sin plan de cuentas"}
          </StatusPill>
        </StatusBadges>
      </PageHeader>

      <SetupBanner
        periodoActivo={periodoActivo}
        planCuentas={planCuentas || []}
        onSeedPlanCuentas={() => seedMutation.mutate()}
        onCrearEjercicio={handleCrearEjercicio}
        seedLoading={seedMutation.isPending}
      />

      <TabsBar>
        <Tabs
          value={tab}
          onChange={(_, v) => setTab(v)}
          variant="scrollable"
          scrollButtons="auto"
          sx={{
            "& .MuiTabs-indicator": { background: "#f88533" },
            "& .Mui-selected": { color: "#f88533 !important" },
            minHeight: 44,
          }}
        >
          {TABS.map(({ label, icon }) => (
            <Tab
              key={label}
              label={
                <TabLabel>
                  <Icon icon={icon} />
                  {label}
                </TabLabel>
              }
              sx={{ minHeight: 44, fontSize: 13, textTransform: "none", fontWeight: 600, color: "inherit" }}
            />
          ))}
        </Tabs>
      </TabsBar>

      <TabContent>
        <TabPanel value={tab} index={0}>
          <AsientosTab />
        </TabPanel>
        <TabPanel value={tab} index={1}>
          <ReportesContablesTab />
        </TabPanel>
        <TabPanel value={tab} index={2}>
          <ConciliacionContablePage />
        </TabPanel>
        <TabPanel value={tab} index={3}>
          <PlanCuentasTab />
        </TabPanel>
        <TabPanel value={tab} index={4}>
          <EjerciciosTab onCrearEjercicioRef={crearEjRef} />
        </TabPanel>
        <TabPanel value={tab} index={5}>
          <MapeoCuentasTab />
        </TabPanel>
        <TabPanel value={tab} index={6}>
          <CentrosCostoTab />
        </TabPanel>
        <TabPanel value={tab} index={7}>
          <TipoCambioTab />
        </TabPanel>
      </TabContent>
    </PageWrapper>
  );
}

// ── Styles ────────────────────────────────────────────────────────────────────
const PageWrapper = styled.div`
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
  @media (max-width: 768px) {
    padding: 14px;
  }
`;
const PageHeader = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 12px;
`;
const HeaderLeft = styled.div`
  display: flex;
  align-items: center;
  gap: 14px;
`;
const PageIcon = styled.div`
  width: 48px;
  height: 48px;
  border-radius: 14px;
  background: linear-gradient(135deg, #f88533 0%, #ff6b6b 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  svg {
    width: 26px;
    height: 26px;
    color: #fff;
  }
`;
const PageTitle = styled.h1`
  margin: 0;
  font-size: 22px;
  font-weight: 800;
  color: ${({ theme }) => theme.text};
`;
const PageSubtitle = styled.p`
  margin: 0;
  font-size: 13px;
  color: ${({ theme }) => theme.text}88;
`;
const StatusBadges = styled.div`
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
`;
const StatusPill = styled.div`
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  background: ${({ theme }) => theme.bg3};
  color: ${({ $ok, theme }) => ($ok ? "#22c55e" : theme.text + "88")};
  border: 1px solid ${({ $ok }) => ($ok ? "#22c55e44" : "transparent")};
  svg {
    width: 14px;
    height: 14px;
  }
`;
const TabsBar = styled.div`
  background: ${({ theme }) => theme.bg2};
  border-radius: 10px 10px 0 0;
  border: 1px solid ${({ theme }) => theme.color2};
  border-bottom: none;
  padding: 0 8px;
`;
const TabContent = styled.div`
  background: ${({ theme }) => theme.bg1};
  border-radius: 0 0 12px 12px;
  border: 1px solid ${({ theme }) => theme.color2};
  border-top: none;
  padding: 20px;
  min-height: 400px;
`;
const TabLabel = styled.span`
  display: flex;
  align-items: center;
  gap: 7px;
  svg {
    width: 16px;
    height: 16px;
  }
`;
