import { Icon } from "@iconify/react";
import {
  Box,
  Paper,
  Tab,
  Tabs,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useSearchParams } from "react-router-dom";
import styled from "styled-components";
import { useAuthStore } from "../store/AuthStore";
import { TourTrigger } from "../tours/components/TourTrigger";
import { contactosSteps } from "../tours/definitions/contactosTour";
import { ProveedoresTab } from "../components/contactos/ProveedoresTab";
import { AgentesTransporteTab } from "../components/contactos/transporte/AgentesTransporteTab";
import { ChofereTab } from "../components/contactos/transporte/ChofereTab";
import { TransportistasTab } from "../components/contactos/transporte/TransportistasTab";
import { VehiculosTab } from "../components/contactos/transporte/VehiculosTab";
import { ClientesListConfig } from "../components/organismos/ClientesDesign/ClientesListConfig";
import { VendedoresCobradoresModule } from "../components/organismos/VendedoresCobradoresDesign/VendedoresCobradoresModule";
import { ScreenGuia } from "../components/_standards";

const GUIA_PASOS = [
  {
    icon: "lucide:user",
    color: "#3b82f6",
    titulo: "1. Clientes",
    desc: "Registrá tus clientes con datos fiscales SIFEN, lista de precios y cobrador asignado.",
  },
  {
    icon: "lucide:building-2",
    color: "#f59e0b",
    titulo: "2. Proveedores",
    desc: "Mantené el alta de proveedores, geografía y datos de contacto para compras.",
  },
  {
    icon: "lucide:users",
    color: "#22c55e",
    titulo: "3. Equipo comercial",
    desc: "Gestioná vendedores, cobradores y transportistas según los módulos contratados.",
  },
];

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

export const Contactos = () => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("md"));
  const [searchParams, setSearchParams] = useSearchParams();
  const hasModule = useAuthStore((s) => s.hasModule);
  const hasPermission = useAuthStore((s) => s.hasPermission);
  const ecommerceClientesOnly = hasModule("ECOMMERCE") && !hasModule("VENTAS");

  const canVerRemision = hasPermission("VENTAS", "VEN_NR_NOTA_REMISION_VER");
  const canVerVendedores = hasPermission("COBRANZAS", "COB_CBR_COBRADOR_VER");

  const tabs = [
    { slug: "clientes",             icon: "lucide:user",           label: "Clientes",                content: <ClientesListConfig /> },
    ...(!ecommerceClientesOnly ? [
      { slug: "proveedores",        icon: "lucide:building-2",     label: "Proveedores",             content: <ProveedoresTab /> },
    ] : []),
    ...(!ecommerceClientesOnly && canVerVendedores ? [
      { slug: "vendedores",         icon: "lucide:users",          label: "Vendedores y Cobradores", content: <VendedoresCobradoresModule /> },
    ] : []),
    ...(!ecommerceClientesOnly && canVerRemision ? [
      { slug: "transportistas",     icon: "lucide:truck",          label: "Transportistas",          content: <TransportistasTab /> },
      { slug: "choferes",           icon: "lucide:steering-wheel", label: "Choferes",                content: <ChofereTab /> },
      { slug: "vehiculos",          icon: "lucide:car",            label: "Vehículos",               content: <VehiculosTab /> },
      { slug: "agentes-transporte", icon: "lucide:headset",        label: "Agentes Transporte",      content: <AgentesTransporteTab /> },
    ] : []),
  ];

  const tabSlug = searchParams.get("tab") ?? "clientes";
  const tabValue = Math.max(0, tabs.findIndex((t) => t.slug === tabSlug));

  const handleTabChange = (_, newValue) => {
    setSearchParams({ tab: tabs[newValue]?.slug ?? "clientes" }, { replace: true });
  };

  return (
    <Container>
      <ScreenGuia
        titulo="¿Cómo funciona el módulo de Contactos?"
        intro="Centralizá la gestión de personas que interactúan con tu empresa: clientes, proveedores y equipo comercial."
        pasos={GUIA_PASOS}
      />

      <HeaderBar id="contactos-header">
        <div className="title-block">
          <Icon icon="lucide:contact-round" width={24} />
          <div>
            <div className="title">Contactos</div>
            <div className="subtitle">Clientes, proveedores y equipo comercial</div>
          </div>
        </div>
        <TourTrigger steps={contactosSteps} tourKey="contactos" autoStart={true} />
      </HeaderBar>

      <Paper variant="outlined" sx={{ borderRadius: 2, overflow: "hidden", flex: 1, display: "flex", flexDirection: "column", minHeight: 0 }}>
        <Box id="contactos-tabs" sx={{ borderBottom: 1, borderColor: "divider" }}>
          <Tabs
            value={tabValue}
            onChange={handleTabChange}
            variant="scrollable"
            scrollButtons="auto"
            sx={{
              "& .MuiTab-root": {
                minHeight: 48,
                textTransform: "none",
                fontSize: "0.9rem",
              },
            }}
          >
            {tabs.map((tab, i) => (
              <Tab
                key={i}
                icon={<Icon icon={tab.icon} width={18} />}
                iconPosition="start"
                label={isMobile ? undefined : tab.label}
              />
            ))}
          </Tabs>
        </Box>

        <Box sx={{ p: { xs: 1, md: 2 }, flex: 1, overflow: "auto", minHeight: 0 }}>
          {tabs.map((tab, i) => (
            <TabPanel key={i} value={tabValue} index={i}>
              {tab.content}
            </TabPanel>
          ))}
        </Box>
      </Paper>
    </Container>
  );
};

const Container = styled.div`
  /* min-height (no height fija) → crece con el contenido; único scroll = el del body. */
  min-height: calc(100vh - 50px);
  margin-top: 50px;
  padding: 15px;
  display: flex;
  flex-direction: column;
  gap: 1rem;

  @media (max-width: 600px) {
    padding: 8px;
    margin-top: 45px;
  }
`;

const HeaderBar = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 0.75rem;

  .title-block {
    display: flex;
    align-items: center;
    gap: 0.7rem;
    color: ${(p) => p.theme.text};
    .title { font-size: 1.15rem; font-weight: 700; line-height: 1.2; }
    .subtitle { font-size: 0.78rem; color: ${(p) => p.theme.textSecondary}; }
  }
`;
