import { Icon } from "@iconify/react";
import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import styled from "styled-components";
import { DashboardEjecutivo } from "../components/organismos/suscripciones/DashboardEjecutivo";
import { GestionComisiones } from "../components/organismos/suscripciones/GestionComisiones";
import { GestionPlanes } from "../components/organismos/suscripciones/GestionPlanes";
import { GestionSuscripciones } from "../components/organismos/suscripciones/GestionSuscripciones";
import { RedEmpresarial } from "../components/organismos/suscripciones/RedEmpresarial";
import { ConsumoIaHolding } from "../components/organismos/suscripciones/ConsumoIaHolding";
import { Resellers } from "../components/organismos/suscripciones/Resellers";
import { ValidarComprobantes } from "../components/organismos/suscripciones/ValidarComprobantes";
import { SuscripcionesTemplate } from "../components/templates/SuscripcionesTemplate";
import { UserAuth } from "../context/AuthContent";

export function Suscripciones() {
  const { user } = UserAuth();
  const [searchParams, setSearchParams] = useSearchParams();
  const [userType, setUserType] = useState("subsidiario"); // holding, reseller, subsidiario

  // Determinar tipo de usuario basado en la empresa
  useEffect(() => {
    if (user?.empresa) {
      // Lógica para determinar el tipo de empresa
      // Por ahora usamos subsidiario como default
      setUserType(user.empresa.type || "subsidiario");
    }
  }, [user]);

  // Configuración de tabs basada en el tipo de usuario
  const getTabsForUserType = () => {
    if (userType === "holding") {
      return [
        {
          id: "jerarquia",
          label: "Red Empresarial",
          icon: "lucide:network",
          description: "Gestiona tu red de empresas",
        },
        {
          id: "resellers",
          label: "Resellers",
          icon: "lucide:users-2",
          description: "Administra tus socios comerciales",
        },
        {
          id: "comprobantes",
          label: "Comprobantes",
          icon: "lucide:file-check",
          description: "Validar comprobantes de pago",
        },
        {
          id: "comisiones",
          label: "Comisiones",
          icon: "lucide:trending-up",
          description: "Comisiones por pagar y métricas",
        },
        {
          id: "planes",
          label: "Planes",
          icon: "lucide:package",
          description: "Crear y administrar planes",
        },
        {
          id: "metricas",
          label: "Métricas",
          icon: "lucide:bar-chart-3",
          description: "Dashboard ejecutivo",
        },
        {
          id: "consumo-ia",
          label: "Consumo IA",
          icon: "lucide:brain",
          description: "Tokens de IA y cuotas por empresa",
        },
      ];
    }

    if (userType === "reseller") {
      return [
        {
          id: "mis-subsidiarios",
          label: "Mis Subsidiarios",
          icon: "lucide:building-2",
          description: "Empresas que representas",
        },
        {
          id: "mis-comisiones",
          label: "Mis Comisiones",
          icon: "lucide:wallet",
          description: "Comisiones ganadas y pendientes",
        },
        {
          id: "metricas-reseller",
          label: "Mis Métricas",
          icon: "lucide:activity",
          description: "Rendimiento de ventas",
        },
      ];
    }

    return [];
  };

  const tabs = getTabsForUserType();

  // Pestaña activa derivada de la URL (?tab=...). Al refrescar se mantiene.
  // Si la URL no trae una pestaña válida para el tipo de usuario, cae en la primera.
  const urlTab = searchParams.get("tab");
  const activeTab = tabs.find((t) => t.id === urlTab)?.id ?? tabs[0]?.id ?? "";
  const setActiveTab = (id) => setSearchParams({ tab: id }, { replace: true });

  return (
    <SuscripcionesTemplate>
      <Container>
        {/* Header Section */}
        <HeaderSection>
          <HeaderContent>
            <TitleSection>
              <MainTitle>
                <Icon icon="lucide:credit-card" />
                Suscripciones y Comisiones
              </MainTitle>
              <Subtitle>
                Gestiona tu suscripción, red empresarial y comisiones
              </Subtitle>
            </TitleSection>

            {user?.empresa && (
              <CompanyInfo>
                <CompanyBadge $type={userType}>
                  <Icon icon={getCompanyIcon(userType)} />
                  <span>{getCompanyTypeLabel(userType)}</span>
                </CompanyBadge>
                <CompanyName>{user.empresa.razon_social}</CompanyName>
              </CompanyInfo>
            )}
          </HeaderContent>
        </HeaderSection>

        {/* Navigation Tabs */}
        <TabsSection>
          <TabsContainer>
            {tabs.map((tab) => (
              <TabButton
                key={tab.id}
                $active={activeTab === tab.id}
                onClick={() => setActiveTab(tab.id)}
                title={tab.description}
              >
                <Icon icon={tab.icon} />
                <TabLabel>{tab.label}</TabLabel>
              </TabButton>
            ))}
          </TabsContainer>
        </TabsSection>

        {/* Content Area */}
        <ContentSection>
          {renderTabContent(activeTab, userType, user)}
        </ContentSection>
      </Container>
    </SuscripcionesTemplate>
  );
}

// Funciones auxiliares
const getCompanyIcon = (type) => {
  switch (type) {
    case "holding":
      return "lucide:building";
    case "reseller":
      return "lucide:handshake";
    default:
      return "lucide:building-2";
  }
};

const getCompanyTypeLabel = (type) => {
  switch (type) {
    case "holding":
      return "Holding";
    case "reseller":
      return "Reseller";
    default:
      return "Subsidiario";
  }
};

const renderTabContent = (activeTab, userType, user) => {
  switch (activeTab) {
    case "jerarquia":
      return <JerarquiaContent user={user} />;
    case "resellers":
      return <ResellersContent user={user} />;
    case "planes":
      return <PlanesContent />;
    case "comprobantes":
      return <ComprobantesContent />;
    case "comisiones":
      return <ComisionesContent user={user} />;
    case "metricas":
      return <MetricasContent user={user} />;
    case "consumo-ia":
      return <ConsumoIaHolding />;
    case "mis-subsidiarios":
      return <MisSubsidiariosContent user={user} />;
    case "mis-comisiones":
      return <MisComisionesContent user={user} />;
    case "metricas-reseller":
      return <MetricasResellerContent user={user} />;
    default:
      return null;
  }
};

// Componentes de contenido
const JerarquiaContent = () => <RedEmpresarial />;

const ResellersContent = () => <GestionSuscripciones />;

const PlanesContent = () => <GestionPlanes />;

const ComprobantesContent = () => <ValidarComprobantes />;

const ComisionesContent = () => <GestionComisiones />;

const MetricasContent = () => <DashboardEjecutivo />;

const MisSubsidiariosContent = () => <GestionSuscripciones />;

const MisComisionesContent = () => <Resellers />;

const MetricasResellerContent = () => (
  <ContentPlaceholder>
    <Icon icon="lucide:activity" size={48} />
    <h3>Mis Métricas</h3>
    <p>Rendimiento de tus ventas como reseller</p>
  </ContentPlaceholder>
);

// Styled Components
const Container = styled.div`
  background: ${({ theme }) => theme.body};
  padding: 0;
  overflow: hidden;
  max-width: 100%;
`;

const HeaderSection = styled.div`
  background: linear-gradient(
    135deg,
    ${({ theme }) => theme.bg3} 0%,
    ${({ theme }) => theme.bg4} 100%
  );
  border-bottom: 1px solid ${({ theme }) => theme.bg4};
  padding: 0.6rem 1.5rem;

  @media (max-width: 768px) {
    padding: 0.5rem 1rem;
  }
`;

const HeaderContent = styled.div`
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;

  @media (max-width: 768px) {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
`;

const TitleSection = styled.div`
  flex: 1;
`;

const MainTitle = styled.h1`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.4rem;
  font-weight: 700;
  color: ${({ theme }) => theme.text};
  margin: 0 0 0.15rem 0;

  svg {
    color: #f88533;
    width: 1.4rem;
    height: 1.4rem;
  }

  @media (max-width: 768px) {
    font-size: 1.2rem;

    svg {
      width: 1.2rem;
      height: 1.2rem;
    }
  }
`;

const Subtitle = styled.p`
  font-size: 0.8rem;
  color: ${({ theme }) => theme.text}cc;
  margin: 0;

  @media (max-width: 768px) {
    font-size: 0.75rem;
  }
`;

const CompanyInfo = styled.div`
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 0.5rem;

  @media (max-width: 768px) {
    align-items: flex-start;
    width: 100%;
  }
`;

const CompanyBadge = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: ${({ $type }) =>
    $type === "holding"
      ? "linear-gradient(135deg, #f8853315 0%, #ff6b6b15 100%)"
      : $type === "reseller"
        ? "linear-gradient(135deg, #3b82f615 0%, #06b6d415 100%)"
        : "linear-gradient(135deg, #10b98115 0%, #059f6915 100%)"};
  border: 1px solid
    ${({ $type }) =>
      $type === "holding"
        ? "#f8853340"
        : $type === "reseller"
          ? "#3b82f640"
          : "#10b98140"};
  border-radius: 8px;

  svg {
    width: 1rem;
    height: 1rem;
    color: ${({ $type }) =>
      $type === "holding"
        ? "#f88533"
        : $type === "reseller"
          ? "#3b82f6"
          : "#10b981"};
  }

  span {
    font-size: 0.75rem;
    font-weight: 600;
    color: ${({ $type }) =>
      $type === "holding"
        ? "#f88533"
        : $type === "reseller"
          ? "#3b82f6"
          : "#10b981"};
  }
`;

const CompanyName = styled.h3`
  font-size: 0.9rem;
  font-weight: 600;
  color: ${({ theme }) => theme.text};
  margin: 0;
  text-align: right;

  @media (max-width: 768px) {
    text-align: left;
  }
`;

const TabsSection = styled.div`
  background: ${({ theme }) => theme.body};
  border-bottom: 1px solid ${({ theme }) => theme.bg4};
  padding: 0 1.5rem;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
  &::-webkit-scrollbar {
    display: none;
  }

  @media (max-width: 768px) {
    padding: 0 0.5rem;
  }
`;

const TabsContainer = styled.div`
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  gap: 0.15rem;
`;

const TabButton = styled.button`
  display: inline-flex;
  align-items: center;
  gap: 0.4rem;
  padding: 0.55rem 0.75rem;
  border: none;
  background: ${({ $active, theme }) => ($active ? theme.bg3 : "transparent")};
  color: ${({ $active, theme }) => ($active ? theme.text : `${theme.text}b0`)};
  cursor: pointer;
  border-radius: 8px 8px 0 0;
  transition: all 0.15s ease;
  white-space: nowrap;
  border-bottom: 2px solid
    ${({ $active }) => ($active ? "#f88533" : "transparent")};
  flex-shrink: 0;

  svg {
    width: 1.05rem;
    height: 1.05rem;
    flex-shrink: 0;
    color: ${({ $active }) => ($active ? "#f88533" : "currentColor")};
  }

  &:hover {
    background: ${({ theme }) => theme.bg3}40;
    color: ${({ theme }) => theme.text};
  }

  @media (max-width: 768px) {
    padding: 0.5rem 0.55rem;
  }
`;

const TabLabel = styled.span`
  font-size: 0.82rem;
  font-weight: 600;
  line-height: 1.2;

  @media (max-width: 600px) {
    display: none;
  }
`;

const ContentSection = styled.div`
  max-width: 1200px;
  margin: 0 auto;
  padding: 0.75rem 1.5rem;
  overflow-x: hidden;
  min-width: 0;

  @media (max-width: 768px) {
    padding: 0.75rem 0.75rem;
  }
`;

const ContentPlaceholder = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 4rem 2rem;
  background: ${({ theme }) => theme.bg3}20;
  border: 2px dashed ${({ theme }) => theme.bg4};
  border-radius: 12px;
  gap: 1rem;

  svg {
    color: ${({ theme }) => theme.text}60;
  }

  h3 {
    font-size: 1.5rem;
    font-weight: 600;
    color: ${({ theme }) => theme.text};
    margin: 0;
  }

  p {
    font-size: 1rem;
    color: ${({ theme }) => theme.text}80;
    margin: 0;
  }

  @media (max-width: 768px) {
    padding: 3rem 1.5rem;

    h3 {
      font-size: 1.25rem;
    }

    p {
      font-size: 0.9rem;
    }
  }
`;
