import { Icon } from "@iconify/react";
import { useQuery } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import styled from "styled-components";
import { suscripcionesQueries } from "../../../api/suscripciones.service";
import { UserAuth } from "../../../context/AuthContent";
import { useMisSubmodulosActivosQuery } from "../../../hooks/useSubmodulo";
import { AddonBadge } from "../../_standards";
import { PlanUsageCard } from "./PlanUsageCard";

export function MiSuscripcion() {
  const { user } = UserAuth();
  const [showChangeModal, setShowChangeModal] = useState(false);

  // Query para obtener información de la suscripción
  const {
    data: suscripcionData,
    isLoading,
    error,
  } = useQuery({
    ...suscripcionesQueries.miSuscripcion(),
    enabled: !!user?.empresa?.id,
  });

  const suscripcion = suscripcionData?.data ?? suscripcionData;

  if (isLoading) {
    return (
      <Container>
        <LoadingState>
          <Icon icon="lucide:loader-2" className="animate-spin" />
          <span>Cargando información de suscripción...</span>
        </LoadingState>
      </Container>
    );
  }

  if (error) {
    return (
      <Container>
        <ErrorState>
          <Icon icon="lucide:alert-circle" />
          <span>Error al cargar la suscripción</span>
        </ErrorState>
      </Container>
    );
  }

  return (
    <Container>
      {/* Header con estado de suscripción */}
      <HeaderCard>
        <StatusSection>
          <StatusBadge $status={suscripcion?.estado}>
            <Icon
              icon={
                suscripcion?.estado === "Activo"
                  ? "lucide:check-circle"
                  : "lucide:alert-circle"
              }
            />
            <span>{suscripcion?.estado}</span>
          </StatusBadge>
          {suscripcion?.vencido && (
            <AlertBanner>
              <Icon icon="lucide:alert-triangle" />
              <span>
                Tu suscripción ha vencidooo. Renueva para continuar usando el
                sistema.
              </span>
            </AlertBanner>
          )}
        </StatusSection>

        <PlanInfo>
          <PlanTitle>{suscripcion?.plan?.nombre}</PlanTitle>
          <PlanDescription>{suscripcion?.plan?.descripcion}</PlanDescription>
          <PriceSection>
            <Price>
              {suscripcion?.plan?.precio?.toLocaleString()}{" "}
              {suscripcion?.plan?.moneda}
            </Price>
            <PricePeriod>/ mes</PricePeriod>
          </PriceSection>
        </PlanInfo>
      </HeaderCard>

      {/* Grid de información */}
      <InfoGrid>
        <InfoCard>
          <InfoIcon>
            <Icon icon="lucide:calendar" />
          </InfoIcon>
          <InfoContent>
            <InfoLabel>Período de suscripción</InfoLabel>
            <InfoValue>
              Inicio: {suscripcion?.fechaInicio}
              <br />
              Fin: {suscripcion?.fechaFin}
            </InfoValue>
          </InfoContent>
        </InfoCard>

        <InfoCard>
          <InfoIcon>
            <Icon icon="lucide:credit-card" />
          </InfoIcon>
          <InfoContent>
            <InfoLabel>Próximo cobro</InfoLabel>
            <InfoValue>{suscripcion?.proximoCobro}</InfoValue>
          </InfoContent>
        </InfoCard>

        <InfoCard>
          <InfoIcon>
            <Icon icon="lucide:building-2" />
          </InfoIcon>
          <InfoContent>
            <InfoLabel>Empresa</InfoLabel>
            <InfoValue>{user?.empresa?.razon_social}</InfoValue>
          </InfoContent>
        </InfoCard>

        <InfoCard>
          <InfoIcon>
            <Icon icon="lucide:user" />
          </InfoIcon>
          <InfoContent>
            <InfoLabel>Responsable</InfoLabel>
            <InfoValue>
              {user?.nombres} {user?.apellidos}
            </InfoValue>
          </InfoContent>
        </InfoCard>
      </InfoGrid>

      {/* Acciones */}
      <ActionsSection>
        <ActionCard>
          <ActionIcon>
            <Icon icon="lucide:refresh-cw" />
          </ActionIcon>
          <ActionContent>
            <ActionTitle>Cambiar Plan</ActionTitle>
            <ActionDescription>
              Actualiza tu suscripción a un plan superior
            </ActionDescription>
          </ActionContent>
          <ActionButton onClick={() => setShowChangeModal(true)}>
            <Icon icon="lucide:arrow-right" />
          </ActionButton>
        </ActionCard>

        <ActionCard>
          <ActionIcon>
            <Icon icon="lucide:file-text" />
          </ActionIcon>
          <ActionContent>
            <ActionTitle>Ver Historial de Pagos</ActionTitle>
            <ActionDescription>
              Consulta tus facturas y pagos anteriores
            </ActionDescription>
          </ActionContent>
          <ActionButton>
            <Icon icon="lucide:arrow-right" />
          </ActionButton>
        </ActionCard>

        <ActionCard>
          <ActionIcon>
            <Icon icon="lucide:help-circle" />
          </ActionIcon>
          <ActionContent>
            <ActionTitle>Soporte</ActionTitle>
            <ActionDescription>
              Para cambiar de plan o renovar tu suscripción, contacta a soporte
            </ActionDescription>
          </ActionContent>
          <ActionButton>
            <Icon icon="lucide:external-link" />
          </ActionButton>
        </ActionCard>
      </ActionsSection>

      {/* Módulos y submódulos contratados */}
      <ModulosContratadosCard />

      {/* Uso del plan */}
      <PlanUsageCard />

      {/* Nota informativa */}
      <InfoNote>
        <Icon icon="lucide:info" />
        <span>
          Para cambiar de plan o renovar tu suscripción, contacta a soporte.
        </span>
      </InfoNote>
    </Container>
  );
}

function ModulosContratadosCard() {
  const { data, isLoading, isError } = useMisSubmodulosActivosQuery();

  const grupos = useMemo(() => {
    const map = new Map();
    for (const s of data ?? []) {
      const key = s.modulo_codigo || "OTROS";
      if (!map.has(key)) {
        map.set(key, {
          codigo: key,
          descripcion: s.modulo_descripcion || key,
          icono: s.modulo_icono,
          items: [],
        });
      }
      map.get(key).items.push(s);
    }
    return Array.from(map.values()).sort((a, b) =>
      a.descripcion.localeCompare(b.descripcion),
    );
  }, [data]);

  return (
    <ModulosWrapper>
      <ModulosHeader>
        <Icon icon="mdi:view-grid-outline" />
        <span>Módulos contratados</span>
        <small>
          {data?.length ?? 0} submódulo{(data?.length ?? 0) === 1 ? "" : "s"} activo{(data?.length ?? 0) === 1 ? "" : "s"}
        </small>
      </ModulosHeader>

      {isLoading && (
        <ModulosEmpty>
          <Icon icon="lucide:loader-2" className="animate-spin" />
          <span>Cargando módulos…</span>
        </ModulosEmpty>
      )}

      {isError && (
        <ModulosEmpty $error>
          <Icon icon="lucide:alert-circle" />
          <span>No se pudieron cargar los módulos contratados.</span>
        </ModulosEmpty>
      )}

      {!isLoading && !isError && grupos.length === 0 && (
        <ModulosEmpty>
          <Icon icon="mdi:package-variant" />
          <span>Tu plan aún no tiene módulos activos.</span>
        </ModulosEmpty>
      )}

      {grupos.length > 0 && (
        <ModulosGrid>
          {grupos.map((g) => (
            <ModuloGroup key={g.codigo}>
              <ModuloGroupHeader>
                {g.icono && <Icon icon={g.icono} />}
                <span>{g.descripcion}</span>
              </ModuloGroupHeader>
              <SubmoduloList>
                {g.items.map((s) => (
                  <SubmoduloItem key={s.codigo}>
                    {s.icono && <Icon icon={s.icono} />}
                    <span>{s.descripcion}</span>
                    {s.es_addon && <AddonBadge />}
                  </SubmoduloItem>
                ))}
              </SubmoduloList>
            </ModuloGroup>
          ))}
        </ModulosGrid>
      )}

      <UpsellCta>
        <Icon icon="mdi:puzzle-plus" />
        <div>
          <strong>¿Necesitás más módulos o addons?</strong>
          <p>Contactá a tu administrador del holding o a soporte para sumar funcionalidades a tu plan.</p>
        </div>
        <a href="mailto:soporte@novasis.com.py?subject=Solicitud%20de%20módulos%20adicionales">
          <Icon icon="lucide:mail" />
          Solicitar
        </a>
      </UpsellCta>
    </ModulosWrapper>
  );
}

// Styled Components
const Container = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  max-width: 1000px;
  margin: 0 auto;
`;

const LoadingState = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  padding: 4rem 2rem;
  color: ${({ theme }) => theme.text}80;

  svg {
    width: 2rem;
    height: 2rem;
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
`;

const ErrorState = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  padding: 4rem 2rem;
  color: #ef4444;

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

const HeaderCard = styled.div`
  background: ${({ theme }) => theme.bg3};
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 14px;
  padding: 1.25rem;
  display: flex;
  flex-direction: column;
  gap: 0.75rem;

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

const StatusSection = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
`;

const StatusBadge = styled.div`
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border-radius: 8px;
  font-size: 0.875rem;
  font-weight: 600;
  width: fit-content;

  background: ${({ $status }) =>
    $status === "Activo" ? "#10b98120" : "#ef444420"};
  color: ${({ $status }) => ($status === "Activo" ? "#10b981" : "#ef4444")};
  border: 1px solid
    ${({ $status }) => ($status === "Activo" ? "#10b98140" : "#ef444440")};

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

const AlertBanner = styled.div`
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1rem;
  background: #ef444415;
  border: 1px solid #ef444430;
  border-radius: 8px;
  color: #ef4444;
  font-size: 0.875rem;

  svg {
    width: 1.25rem;
    height: 1.25rem;
    flex-shrink: 0;
  }
`;

const PlanInfo = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
`;

const PlanTitle = styled.h2`
  font-size: 1.2rem;
  font-weight: 700;
  color: ${({ theme }) => theme.text};
  margin: 0;

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

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

const PriceSection = styled.div`
  display: flex;
  align-items: baseline;
  gap: 0.5rem;
  margin-top: 0.25rem;
`;

const Price = styled.span`
  font-size: 1.5rem;
  font-weight: 700;
  color: #f88533;

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

const PricePeriod = styled.span`
  font-size: 1rem;
  color: ${({ theme }) => theme.text}60;
`;

const InfoGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 0.6rem;

  @media (max-width: 768px) {
    grid-template-columns: repeat(2, 1fr);
  }
  @media (max-width: 450px) {
    grid-template-columns: 1fr;
  }
`;

const InfoCard = styled.div`
  background: ${({ theme }) => theme.bg3};
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 10px;
  padding: 0.85rem 1rem;
  display: flex;
  align-items: center;
  gap: 0.75rem;
  transition: all 0.15s ease;

  &:hover {
    border-color: ${({ theme }) => theme.bg5};
  }
`;

const InfoIcon = styled.div`
  width: 2rem;
  height: 2rem;
  background: #f8853320;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;

  svg {
    width: 1rem;
    height: 1rem;
    color: #f88533;
  }
`;

const InfoContent = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  flex: 1;
`;

const InfoLabel = styled.span`
  font-size: 0.75rem;
  font-weight: 600;
  color: ${({ theme }) => theme.text}80;
  text-transform: uppercase;
  letter-spacing: 0.05em;
`;

const InfoValue = styled.span`
  font-size: 0.875rem;
  color: ${({ theme }) => theme.text};
  line-height: 1.4;
`;

const ActionsSection = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
`;

const ActionCard = styled.div`
  background: ${({ theme }) => theme.bg3};
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 10px;
  padding: 0.85rem 1rem;
  display: flex;
  align-items: center;
  gap: 0.75rem;
  cursor: pointer;
  transition: all 0.15s ease;

  &:hover {
    border-color: #f88533;
    background: ${({ theme }) => theme.bg3}cc;
  }
`;

const ActionIcon = styled.div`
  width: 2.25rem;
  height: 2.25rem;
  background: #f8853315;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;

  svg {
    width: 1.1rem;
    height: 1.1rem;
    color: #f88533;
  }
`;

const ActionContent = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  flex: 1;
`;

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

const ActionDescription = styled.p`
  font-size: 0.78rem;
  color: ${({ theme }) => theme.text}80;
  margin: 0;
  line-height: 1.3;
`;

const ActionButton = styled.div`
  width: 2rem;
  height: 2rem;
  background: #f8853320;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;

  svg {
    width: 1rem;
    height: 1rem;
    color: #f88533;
  }
`;

const InfoNote = styled.div`
  display: flex;
  align-items: center;
  gap: 0.6rem;
  padding: 0.7rem 1rem;
  background: #3b82f615;
  border: 1px solid #3b82f630;
  border-radius: 8px;
  color: #3b82f6;
  font-size: 0.8rem;

  svg {
    width: 1rem;
    height: 1rem;
    flex-shrink: 0;
  }
`;

const ModulosWrapper = styled.div`
  background: ${({ theme }) => theme.bg3};
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 12px;
  padding: 1rem 1.1rem;
  display: flex;
  flex-direction: column;
  gap: 0.85rem;
`;

const ModulosHeader = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.9rem;
  font-weight: 600;
  color: ${({ theme }) => theme.text};

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

  small {
    margin-left: auto;
    font-size: 0.72rem;
    font-weight: 500;
    color: ${({ theme }) => theme.text}80;
  }
`;

const ModulosEmpty = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 1rem;
  border-radius: 8px;
  background: ${({ $error }) => ($error ? "#ef444415" : "#3b82f60d")};
  color: ${({ $error, theme }) => ($error ? "#ef4444" : `${theme.text}90`)};
  font-size: 0.82rem;

  svg {
    width: 1rem;
    height: 1rem;
    flex-shrink: 0;
  }

  .animate-spin {
    animation: spin 1s linear infinite;
  }
`;

const ModulosGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 0.6rem;
`;

const ModuloGroup = styled.div`
  background: ${({ theme }) => theme.bg2};
  border: 1px solid ${({ theme }) => theme.bg4};
  border-radius: 10px;
  padding: 0.6rem 0.75rem;
  display: flex;
  flex-direction: column;
  gap: 0.45rem;
`;

const ModuloGroupHeader = styled.div`
  display: flex;
  align-items: center;
  gap: 0.4rem;
  font-size: 0.78rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  color: ${({ theme }) => theme.text};

  svg {
    width: 0.95rem;
    height: 0.95rem;
    color: #f88533;
  }
`;

const SubmoduloList = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
`;

const SubmoduloItem = styled.div`
  display: flex;
  align-items: center;
  gap: 0.4rem;
  font-size: 0.82rem;
  color: ${({ theme }) => theme.text}cc;
  padding: 0.2rem 0;

  svg {
    width: 0.9rem;
    height: 0.9rem;
    color: ${({ theme }) => theme.text}80;
  }
`;

const UpsellCta = styled.div`
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.85rem 1rem;
  background: linear-gradient(135deg, #f8853310 0%, #3b82f610 100%);
  border: 1px dashed #f8853360;
  border-radius: 10px;

  > svg {
    width: 1.5rem;
    height: 1.5rem;
    color: #f88533;
    flex-shrink: 0;
  }

  div {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 0.15rem;
  }

  strong {
    font-size: 0.85rem;
    color: ${({ theme }) => theme.text};
  }

  p {
    margin: 0;
    font-size: 0.75rem;
    color: ${({ theme }) => theme.text}99;
    line-height: 1.35;
  }

  a {
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
    padding: 0.45rem 0.85rem;
    border-radius: 8px;
    background: #f88533;
    color: white;
    font-size: 0.78rem;
    font-weight: 600;
    text-decoration: none;
    transition: background 0.15s;
    flex-shrink: 0;

    &:hover {
      background: #e87520;
    }

    svg {
      width: 0.9rem;
      height: 0.9rem;
    }
  }

  @media (max-width: 600px) {
    flex-direction: column;
    align-items: flex-start;
    a {
      width: 100%;
      justify-content: center;
    }
  }
`;
