"use client";

import type { ComponentType, ReactNode } from "react";
import {
  ArrowRight,
  ExternalLink,
  FolderKanban,
  Sparkles,
} from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { getAccessibleAccent } from "@/lib/color-contrast";
import {
  getAddressSummary as getClientAddressSummary,
  getPreferredClientAddress,
  type ClientAddress,
} from "@/lib/client-portal-addresses";

export type ClientPortalClient = {
  id?: string;
  name?: string | null;
  company_name?: string | null;
  document?: string | null;
  email?: string | null;
  phone?: string | null;
  whatsapp?: string | null;
  address_zip?: string | null;
  address_street?: string | null;
  address_number?: string | null;
  address_complement?: string | null;
  address_neighborhood?: string | null;
  address_city?: string | null;
  address_state?: string | null;
  notes?: string | null;
  portal_last_login_at?: string | null;
  avatar_url?: string | null;
  favorites?: string[] | null;
  addresses?: ClientAddress[] | null;
};

export type ClientPortalOrder = {
  id: string;
  number: number;
  status: string;
  total_amount: number;
  created_at: string;
  share_token?: string | null;
};

export type ClientPortalPaymentReceipt = {
  source?: "order" | "catalog" | null;
  provider?: string | null;
  status?: string | null;
  method?: string | null;
  method_label?: string | null;
  conditions_label?: string | null;
  provider_method_id?: string | null;
  payment_type?: string | null;
  installments?: number | null;
  status_detail?: string | null;
  reference?: string | null;
  amount?: number | null;
  currency?: string | null;
  paid_at?: string | null;
  created_at?: string | null;
  environment?: "sandbox" | "production" | string | null;
  payer_name?: string | null;
  payer_email?: string | null;
  payer_document?: string | null;
};

export type SectionId =
  | "overview"
  | "orders"
  | "catalog"
  | "finance"
  | "addresses"
  | "account"
  | "support"
  | "settings"
  | "favorites"
  | "reviews";

export type NavItem = {
  id: SectionId;
  label: string;
  description: string;
  icon: ComponentType<{ className?: string }>;
};

export const ORDER_STATUS_LABEL: Record<string, string> = {
  pending_production: "Aguardando Produção",
  in_production: "Em Produção",
  finished: "Finalizado",
  delivered: "Entregue",
  canceled: "Cancelado",
};

const ORDER_STATUS_DESCRIPTION: Record<string, string> = {
  pending_production: "Seu pedido foi confirmado e aguarda início da produção",
  in_production: "Seu pedido está em produção",
  finished: "Seu pedido foi finalizado e está pronto para a próxima etapa",
  delivered: "Entrega concluída com sucesso",
  canceled: "Pedido cancelado",
};

export function hexToRgba(hex: string, alpha: number) {
  const normalized = String(hex || "").trim().replace("#", "");
  const safe =
    normalized.length === 3
      ? normalized
          .split("")
          .map((char) => `${char}${char}`)
          .join("")
      : normalized;

  if (!/^[0-9a-fA-F]{6}$/.test(safe)) return `rgba(68, 37, 167, ${alpha})`;

  const int = parseInt(safe, 16);
  const r = (int >> 16) & 255;
  const g = (int >> 8) & 255;
  const b = int & 255;
  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}

export function formatMoney(value: number) {
  return new Intl.NumberFormat("pt-BR", {
    style: "currency",
    currency: "BRL",
  }).format(Number.isFinite(value) ? value : 0);
}

export function formatDate(value?: string | null) {
  if (!value) return "Nao informado";
  const normalized = String(value).trim();
  const dateOnlyMatch = /^(\d{4})-(\d{2})-(\d{2})$/.exec(normalized);
  const date = dateOnlyMatch
    ? new Date(Number(dateOnlyMatch[1]), Number(dateOnlyMatch[2]) - 1, Number(dateOnlyMatch[3]))
    : new Date(normalized);
  return date.toLocaleDateString("pt-BR", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

export function formatDateTime(value?: string | null) {
  if (!value) return "Primeiro acesso recente";
  return new Date(value).toLocaleString("pt-BR", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

export function getGreeting() {
  const hour = new Date().getHours();
  if (hour < 12) return "Bom dia";
  if (hour < 18) return "Boa tarde";
  return "Boa noite";
}

export function getInitials(name: string) {
  const parts = name
    .split(" ")
    .map((part) => part.trim())
    .filter(Boolean);

  if (parts.length === 0) return "CL";
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return `${parts[0][0]}${parts[parts.length - 1][0]}`.toUpperCase();
}

export function getProfileCompletion(client: ClientPortalClient) {
  const preferredAddress = getPreferredClientAddress(client.addresses);
  const checks = [
    String(client?.name || "").trim() !== "",
    [client?.email, client?.phone, client?.whatsapp].some((value) => String(value || "").trim() !== ""),
    String(preferredAddress?.zip || client?.address_zip || "").trim() !== "",
    String(preferredAddress?.street || client?.address_street || "").trim() !== "",
    String(preferredAddress?.number || client?.address_number || "").trim() !== "",
    String(preferredAddress?.neighborhood || client?.address_neighborhood || "").trim() !== "",
    String(preferredAddress?.city || client?.address_city || "").trim() !== "",
    String(preferredAddress?.state || client?.address_state || "").trim() !== "",
  ];
  const completed = checks.filter(Boolean).length;
  return Math.round((completed / checks.length) * 100);
}

export function getIncompleteProfileFields(client: ClientPortalClient) {
  const preferredAddress = getPreferredClientAddress(client.addresses);
  const missing: string[] = [];
  if (String(client?.name || "").trim() === "") missing.push("Nome");
  if (![client?.email, client?.phone, client?.whatsapp].some((value) => String(value || "").trim() !== "")) {
    missing.push("Contato");
  }
  if (String(preferredAddress?.zip || client?.address_zip || "").trim() === "") missing.push("CEP");
  if (String(preferredAddress?.street || client?.address_street || "").trim() === "") missing.push("Rua");
  if (String(preferredAddress?.number || client?.address_number || "").trim() === "") missing.push("Numero");
  if (String(preferredAddress?.neighborhood || client?.address_neighborhood || "").trim() === "") missing.push("Bairro");
  if (String(preferredAddress?.city || client?.address_city || "").trim() === "") missing.push("Cidade");
  if (String(preferredAddress?.state || client?.address_state || "").trim() === "") missing.push("UF");
  return missing;
}

export function isClientProfileComplete(client: ClientPortalClient) {
  return getIncompleteProfileFields(client).length === 0;
}

export function getAddressSummary(client: ClientPortalClient) {
  const preferredAddress = getPreferredClientAddress(client.addresses);
  return (
    getClientAddressSummary(preferredAddress) ||
    getClientAddressSummary({
      street: client?.address_street,
      number: client?.address_number,
      complement: client?.address_complement,
      neighborhood: client?.address_neighborhood,
      city: client?.address_city,
      state: client?.address_state,
      zip: client?.address_zip,
    })
  );
}

export function buildSparklineValues(orders: ClientPortalOrder[]) {
  if (orders.length === 0) return [6, 10, 8, 12, 9, 11, 10];
  const values = orders
    .slice(0, 7)
    .map((order) => Math.max(1, Number(order.total_amount || 0)))
    .reverse();
  while (values.length < 7) {
    values.unshift(values[0] || 1);
  }
  return values;
}

export function buildSparklinePath(values: number[]) {
  const width = 180;
  const height = 52;
  const min = Math.min(...values);
  const max = Math.max(...values);
  const range = Math.max(1, max - min);

  return values
    .map((value, index) => {
      const x = (index / Math.max(1, values.length - 1)) * width;
      const y = height - ((value - min) / range) * height;
      return `${x},${y}`;
    })
    .join(" ");
}

export function getStatusMeta(status: string, primaryColor: string) {
  if (status === "delivered") {
    return {
      label: ORDER_STATUS_LABEL[status] || "Em andamento",
      description: ORDER_STATUS_DESCRIPTION[status] || "Pedido atualizado",
      backgroundColor: "#ecfdf3",
      color: "#027a48",
      borderColor: "#a7f3d0",
    };
  }

  if (status === "canceled") {
    return {
      label: ORDER_STATUS_LABEL[status] || "Em andamento",
      description: ORDER_STATUS_DESCRIPTION[status] || "Pedido atualizado",
      backgroundColor: "#fef2f2",
      color: "#b91c1c",
      borderColor: "#fecaca",
    };
  }

  if (status === "finished") {
    return {
      label: ORDER_STATUS_LABEL[status] || "Em andamento",
      description: ORDER_STATUS_DESCRIPTION[status] || "Pedido atualizado",
      backgroundColor: "#eff6ff",
      color: "#1d4ed8",
      borderColor: "#bfdbfe",
    };
  }

  return {
    label: ORDER_STATUS_LABEL[status] || "Em andamento",
    description: ORDER_STATUS_DESCRIPTION[status] || "Pedido atualizado",
    backgroundColor: hexToRgba(primaryColor, 0.1),
    color: primaryColor,
    borderColor: hexToRgba(primaryColor, 0.18),
  };
}

export function clampPage(page: number, totalPages: number) {
  if (totalPages <= 1) return 1;
  return Math.min(Math.max(page, 1), totalPages);
}

export function PremiumCard({
  children,
  className = "",
}: {
  children: ReactNode;
  className?: string;
}) {
  return (
    <div
      className={`rounded-3xl border border-white/80 bg-white/95 shadow-[0_32px_64px_rgba(15,23,42,0.06)] backdrop-blur-2xl ${className}`}
    >
      {children}
    </div>
  );
}

export function SectionHeader({
  eyebrow,
  title,
  description,
  action,
}: {
  eyebrow: string;
  title: string;
  description: string;
  action?: ReactNode;
}) {
  return (
    <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
      <div className="space-y-2">
        <div className="text-[11px] font-semibold uppercase tracking-[0.22em] text-zinc-400">
          {eyebrow}
        </div>
        <div>
          <h2 className="text-2xl font-semibold tracking-[-0.04em] text-zinc-950">{title}</h2>
          {description ? <p className="mt-1 text-sm text-zinc-500">{description}</p> : null}
        </div>
      </div>
      {action}
    </div>
  );
}

export function AvatarBadge({
  customerName,
  avatarUrl,
  primaryColor,
  size,
}: {
  customerName: string;
  avatarUrl: string;
  primaryColor: string;
  size: "sm" | "md" | "lg";
}) {
  const sizeClass =
    size === "sm" ? "h-10 w-10" : size === "md" ? "h-12 w-12" : "h-16 w-16";

  return (
    <div
      className={`${sizeClass} overflow-hidden rounded-[20px] border border-white/80 bg-white shadow-[0_12px_30px_rgba(15,23,42,0.08)]`}
    >
      {avatarUrl ? (
        <Image
          src={avatarUrl}
          alt={customerName}
          width={80}
          height={80}
          className="h-full w-full object-cover"
          unoptimized
        />
      ) : (
        <div
          className="flex h-full w-full items-center justify-center text-sm font-black text-white"
          style={{
            background: `linear-gradient(135deg, ${primaryColor} 0%, ${hexToRgba(primaryColor, 0.75)} 100%)`,
          }}
        >
          {getInitials(customerName)}
        </div>
      )}
    </div>
  );
}

export function ProgressRing({
  value,
  primaryColor,
}: {
  value: number;
  primaryColor: string;
}) {
  const size = 92;
  const strokeWidth = 8;
  const radius = (size - strokeWidth) / 2;
  const circumference = 2 * Math.PI * radius;
  const dashoffset = circumference - (value / 100) * circumference;

  return (
    <div className="relative flex h-[92px] w-[92px] items-center justify-center">
      <svg width={size} height={size} className="-rotate-90">
        <circle
          cx={size / 2}
          cy={size / 2}
          r={radius}
          stroke="#ebeef4"
          strokeWidth={strokeWidth}
          fill="none"
        />
        <circle
          cx={size / 2}
          cy={size / 2}
          r={radius}
          stroke={getAccessibleAccent(primaryColor, "#FFFFFF", { minRatio: 3 })}
          strokeWidth={strokeWidth}
          fill="none"
          strokeDasharray={circumference}
          strokeDashoffset={dashoffset}
          strokeLinecap="round"
        />
      </svg>
      <div className="absolute text-center">
        <div className="text-2xl font-semibold tracking-[-0.04em] text-zinc-950">{value}%</div>
        <div className="text-[10px] uppercase tracking-[0.18em] text-zinc-400">Perfil</div>
      </div>
    </div>
  );
}

export function StatusPill({
  label,
  color,
  background,
}: {
  label: string;
  color: string;
  background: string;
}) {
  return (
    <span
      className="inline-flex rounded-full px-3 py-1.5 text-xs font-semibold"
      style={{ color, backgroundColor: background }}
    >
      {label}
    </span>
  );
}

export function SnapshotRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-[20px] border border-zinc-100 bg-zinc-50/70 px-4 py-4">
      <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-zinc-400">
        {label}
      </div>
      <div className="mt-2 text-sm font-medium leading-6 text-zinc-800">{value}</div>
    </div>
  );
}

export function InfoTile({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-[24px] border border-zinc-200/80 bg-white p-5">
      <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-zinc-400">
        {label}
      </div>
      <div className="mt-3 text-sm font-medium leading-6 text-zinc-900">{value}</div>
    </div>
  );
}

export function MiniInfoCard({
  icon: Icon,
  title,
  description,
}: {
  icon: ComponentType<{ className?: string }>;
  title: string;
  description: string;
}) {
  return (
    <div className="rounded-[24px] border border-zinc-200/80 bg-white p-5 shadow-[0_16px_36px_rgba(15,23,42,0.05)]">
      <div className="flex h-11 w-11 items-center justify-center rounded-2xl border border-zinc-200 bg-zinc-50 text-zinc-700">
        <Icon className="h-5 w-5" />
      </div>
      <div className="mt-4 text-lg font-semibold tracking-[-0.03em] text-zinc-950">{title}</div>
      {description ? <div className="mt-2 text-sm leading-6 text-zinc-500">{description}</div> : null}
    </div>
  );
}

export function MiniStatCard({
  title,
  value,
  subtitle,
}: {
  title: string;
  value: string;
  subtitle: string;
}) {
  return (
    <div className="rounded-[24px] border border-zinc-200/80 bg-white p-5">
      <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-zinc-400">
        {title}
      </div>
      <div className="mt-3 text-2xl font-semibold tracking-[-0.05em] text-zinc-950">{value}</div>
      <div className="mt-2 text-sm text-zinc-500">{subtitle}</div>
    </div>
  );
}

export function EmptyOrdersCard({
  slug,
  primaryColor,
}: {
  slug: string;
  primaryColor: string;
}) {
  return (
    <div className="rounded-[28px] border border-dashed border-zinc-200 bg-[linear-gradient(180deg,#ffffff_0%,#fafafc_100%)] px-6 py-10 text-center sm:px-10">
      <div
        className="mx-auto flex h-16 w-16 items-center justify-center rounded-[22px]"
        style={{ backgroundColor: hexToRgba(primaryColor, 0.08), color: getAccessibleAccent(primaryColor) }}
      >
        <FolderKanban className="h-7 w-7" />
      </div>
      <h3 className="mt-5 text-xl font-semibold tracking-[-0.04em] text-zinc-950">
        Voce ainda nao tem compras
      </h3>
      <Link
        href={`/${slug}`}
        className="mt-6 inline-flex items-center gap-2 rounded-full px-5 py-3 text-sm font-semibold text-white shadow-[0_18px_40px_rgba(15,23,42,0.14)] transition hover:-translate-y-0.5"
        style={{
          background: `linear-gradient(135deg, ${primaryColor} 0%, ${hexToRgba(primaryColor, 0.8)} 100%)`,
        }}
      >
        Fazer compra
        <ExternalLink className="h-4 w-4" />
      </Link>
    </div>
  );
}

export function TimelineItem({
  title,
  description,
  primaryColor,
  subtle = false,
}: {
  title: string;
  description: string;
  primaryColor: string;
  subtle?: boolean;
}) {
  return (
    <div className="flex gap-4">
      <div className="flex flex-col items-center">
        <span
          className="mt-1 h-3 w-3 rounded-full"
          style={{ backgroundColor: subtle ? hexToRgba(primaryColor, 0.35) : primaryColor }}
        />
        <span className="mt-2 h-full w-px bg-zinc-200" />
      </div>
      <div className="pb-2">
        <div className="text-sm font-semibold text-zinc-950">{title}</div>
        {description ? <div className="mt-1 text-sm leading-6 text-zinc-500">{description}</div> : null}
      </div>
    </div>
  );
}

export function QuickActionButton({
  href,
  onClick,
  icon: Icon,
  label,
  description,
}: {
  href?: string;
  onClick?: () => void;
  icon: ComponentType<{ className?: string }>;
  label: string;
  description: string;
}) {
  const content = (
    <>
      <div className="flex h-11 w-11 items-center justify-center rounded-2xl border border-zinc-200 bg-white text-zinc-700">
        <Icon className="h-5 w-5" />
      </div>
      <div className="min-w-0 flex-1 text-left">
        <div className="text-sm font-semibold text-zinc-950">{label}</div>
        {description ? <div className="mt-1 text-sm text-zinc-500">{description}</div> : null}
      </div>
      <ArrowRight className="h-4 w-4 text-zinc-400" />
    </>
  );

  if (href) {
    return (
      <Link
        href={href}
        className="flex items-center gap-4 rounded-[24px] border border-zinc-200/80 bg-white px-4 py-4 transition hover:-translate-y-0.5 hover:border-zinc-300 hover:shadow-[0_18px_40px_rgba(15,23,42,0.08)]"
      >
        {content}
      </Link>
    );
  }

  return (
    <button
      type="button"
      onClick={onClick}
      className="flex w-full items-center gap-4 rounded-[24px] border border-zinc-200/80 bg-white px-4 py-4 transition hover:-translate-y-0.5 hover:border-zinc-300 hover:shadow-[0_18px_40px_rgba(15,23,42,0.08)]"
    >
      {content}
    </button>
  );
}

export function HeroStat({
  label,
  value,
  helper,
  primaryColor,
}: {
  label: string;
  value: string;
  helper: string;
  primaryColor: string;
}) {
  return (
    <div className="border-b border-zinc-100/80 pb-4 last:border-b-0 last:pb-0">
      <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-zinc-400">
        {label}
      </div>
      <div className="mt-2 text-[32px] font-semibold tracking-[-0.06em] text-zinc-950">{value}</div>
      {helper ? (
        <div className="mt-1 text-sm" style={{ color: getAccessibleAccent(primaryColor) }}>
          {helper}
        </div>
      ) : null}
    </div>
  );
}

export function PremiumMetricCard({
  title,
  value,
  subtitle,
  trend,
  accent,
}: {
  title: string;
  value: string;
  subtitle: string;
  trend: string;
  accent: string;
}) {
  return (
    <PremiumCard className="p-5">
      <div className="flex items-start justify-between gap-4">
        <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-zinc-400">
          {title}
        </div>
        <div className="text-xs font-semibold" style={{ color: accent }}>
          {trend}
        </div>
      </div>
      <div className="mt-5 text-[30px] font-semibold tracking-[-0.06em] text-zinc-950">{value}</div>
      {subtitle ? <div className="mt-1 text-sm text-zinc-500">{subtitle}</div> : null}
    </PremiumCard>
  );
}

export function HeroBadge({ primaryColor }: { primaryColor: string }) {
  return (
    <div
      className="inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-semibold"
      style={{
        backgroundColor: hexToRgba(primaryColor, 0.08),
        borderColor: hexToRgba(primaryColor, 0.14),
        color: getAccessibleAccent(primaryColor),
      }}
    >
      <Sparkles className="h-3.5 w-3.5" />
      Area do cliente
    </div>
  );
}
