"use client";

import { useEffect, useRef, useState, useTransition } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { ChevronLeft, ChevronRight, Loader2, Medal, Search } from "lucide-react";
import { ProductImage } from "@/components/dashboard/product-image";
import { StoreAvatar } from "@/components/dashboard/store-avatar";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useLanguage } from "@/lib/i18n/context";
import { cn } from "@/lib/utils";
import type { CreatorListItemView, CreatorSortKey } from "@/database/creators";

export interface CreatorsFilterState {
  q?: string;
  region?: string;
  minFollowers?: number;
}

const DEBOUNCE_MS = 400;
const SORT_KEYS: CreatorSortKey[] = ["influence", "followers", "videos", "products", "newest"];

const COPY = {
  en: {
    title: "Creator Intelligence",
    description: "Creators synchronized from provider data, linked to the products they promote.",
    search: "Search creators",
    allRegions: "All regions",
    minFollowers: "Min followers",
    sort: "Sort",
    sorts: {
      influence: "Highest influence",
      followers: "Most followers",
      videos: "Most videos",
      products: "Most products",
      newest: "Newest",
    },
    results: "{count} creators found",
    topInfluencers: "Top Influencers",
    more: "More",
    influencers: "Influencers",
    bestProduct: "Best-selling product",
    itemsSold: "Items sold",
    gmv: "GMV",
    unavailable: "Unavailable",
    noData: "No creator data synchronized yet.",
    noDataReason: "Creators are populated by a connected TikTok Shop data source — an admin needs to authorize one first.",
    error: "Creator intelligence could not be loaded.",
    products: "Products",
    followers: "Followers",
    videos: "Videos",
    avgViews: "Avg views",
    quality: "Quality",
    growth: "30d growth",
    view: "View creator",
    previous: "Previous",
    next: "Next",
    pageOf: "Page {page} of {total}",
  },
  es: {
    title: "Inteligencia de creadores",
    description: "Creadores sincronizados desde datos de proveedores, vinculados a los productos que promocionan.",
    search: "Buscar creadores",
    allRegions: "Todas las regiones",
    minFollowers: "Seguidores min.",
    sort: "Ordenar",
    sorts: {
      influence: "Mayor influencia",
      followers: "Mas seguidores",
      videos: "Mas videos",
      products: "Mas productos",
      newest: "Mas recientes",
    },
    results: "{count} creadores encontrados",
    topInfluencers: "Top influencers",
    more: "Ver más",
    influencers: "Creadores",
    bestProduct: "Producto más vendido",
    itemsSold: "Unidades vendidas",
    gmv: "GMV",
    unavailable: "No disponible",
    noData: "Aun no hay datos de creadores sincronizados.",
    noDataReason: "Los creadores se poblan desde una fuente de datos de TikTok Shop conectada — un admin debe autorizar una primero.",
    error: "No se pudo cargar la inteligencia de creadores.",
    products: "Productos",
    followers: "Seguidores",
    videos: "Videos",
    avgViews: "Vistas prom.",
    quality: "Calidad",
    growth: "Crecimiento 30d",
    view: "Ver creador",
    previous: "Anterior",
    next: "Siguiente",
    pageOf: "Pagina {page} de {total}",
  },
} as const;

function formatMoney(value: number | null, currency: string | null, locale: "en" | "es", unavailable = "Unavailable") {
  if (value === null || !currency) return unavailable;
  return new Intl.NumberFormat(locale === "es" ? "es-US" : "en-US", {
    style: "currency",
    currency,
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(value);
}

function formatUnits(value: number | null, locale: "en" | "es", unavailable = "Unavailable") {
  if (value === null) return unavailable;
  return new Intl.NumberFormat(locale === "es" ? "es-US" : "en-US", {
    notation: "compact",
    maximumFractionDigits: 1,
  }).format(value);
}

export function CreatorsPageContent({
  creators,
  regions,
  total,
  page,
  pageSize,
  sort,
  filters,
  loadError,
}: {
  creators: CreatorListItemView[];
  regions: string[];
  total: number;
  page: number;
  pageSize: number;
  sort: CreatorSortKey;
  filters: CreatorsFilterState;
  loadError: boolean;
}) {
  const { locale } = useLanguage();
  const copy = COPY[locale];
  const router = useRouter();
  const pathname = usePathname();
  const [isPending, startTransition] = useTransition();
  const [q, setQ] = useState(filters.q ?? "");
  const [minFollowers, setMinFollowers] = useState(filters.minFollowers?.toString() ?? "");
  const isFirstRender = useRef(true);
  const totalPages = Math.max(1, Math.ceil(total / pageSize));

  function navigate(overrides: Record<string, string | undefined>) {
    const params = new URLSearchParams();
    const current = {
      q,
      region: filters.region,
      minFollowers,
      sort,
      page: String(page),
      pageSize: String(pageSize),
      ...overrides,
    };
    for (const [key, value] of Object.entries(current)) {
      if (value !== undefined && value !== "") params.set(key, value);
    }
    if (!("page" in overrides)) params.set("page", "1");
    startTransition(() => router.push(`${pathname}?${params.toString()}`));
  }

  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
      return;
    }
    const timer = setTimeout(() => navigate({ q, minFollowers }), DEBOUNCE_MS);
    return () => clearTimeout(timer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [q, minFollowers]);

  return (
    <div className="flex w-full max-w-[1500px] flex-col gap-4 pb-8">
      <div className="pt-0.5">
        <h1 className="text-[26px] font-semibold tracking-tight text-foreground sm:text-[28px]">{copy.title}</h1>
        <p className="mt-1 max-w-2xl text-sm text-muted-foreground">{copy.description}</p>
      </div>

      <Card className="rounded-2xl p-4 shadow-xs">
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
          <div className="relative min-w-0">
            <Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" aria-hidden="true" />
            <Input
              value={q}
              onChange={(event) => setQ(event.target.value)}
              placeholder={copy.search}
              className="pl-9"
              aria-label={copy.search}
            />
          </div>
          <Select
            value={filters.region ?? "all"}
            onValueChange={(value) => navigate({ region: value === "all" ? undefined : value })}
          >
            <SelectTrigger aria-label={copy.allRegions} className="w-full">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">{copy.allRegions}</SelectItem>
              {regions.map((region) => (
                <SelectItem key={region} value={region}>
                  {region}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Input
            id="minFollowers"
            type="number"
            min={0}
            value={minFollowers}
            onChange={(event) => setMinFollowers(event.target.value)}
            placeholder={copy.minFollowers}
            aria-label={copy.minFollowers}
          />
          <Select value={sort} onValueChange={(value) => navigate({ sort: value })}>
            <SelectTrigger aria-label={copy.sort} className="w-full">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {SORT_KEYS.map((key) => (
                <SelectItem key={key} value={key}>
                  {copy.sorts[key]}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </Card>

      <Card className="gap-0 overflow-hidden rounded-2xl py-0">
        <div className="flex flex-wrap items-center gap-4 border-b px-5 py-4">
          <div className="flex min-w-0 flex-col gap-0.5">
            <strong className="text-[15px] font-bold text-foreground">{copy.topInfluencers}</strong>
            <span className="text-[11px] text-muted-foreground">
              {copy.results.replace("{count}", new Intl.NumberFormat(locale === "es" ? "es-US" : "en-US").format(total))}
            </span>
          </div>
          <Link href={`${pathname}?sort=influence&page=1`} className="ml-auto flex items-center gap-1 text-sm font-semibold text-primary hover:underline">
            {copy.more}
            <ChevronRight className="size-3.5" />
          </Link>
          {isPending && <Loader2 className="size-4 animate-spin text-muted-foreground" />}
        </div>

        {loadError ? (
          <div className="flex min-h-56 flex-col items-center justify-center gap-1 px-5 text-center">
            <p className="text-sm font-semibold text-foreground">{copy.error}</p>
          </div>
        ) : creators.length === 0 ? (
          <div className="flex min-h-56 flex-col items-center justify-center gap-1 px-6 text-center">
            <p className="text-sm font-semibold text-foreground">{copy.noData}</p>
            <span className="max-w-md text-xs text-muted-foreground">{copy.noDataReason}</span>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[760px] table-fixed border-collapse text-left text-sm">
              <colgroup>
                <col className="w-[6%]" />
                <col className="w-[30%]" />
                <col className="w-[34%]" />
                <col className="w-[14%]" />
                <col className="w-[16%]" />
              </colgroup>
              <thead>
                <tr className="border-b border-border text-xs text-muted-foreground">
                  <th scope="col" className="px-4 py-3 font-medium"><span className="sr-only">Rank</span></th>
                  <th scope="col" className="px-4 py-3 font-medium">{copy.influencers}</th>
                  <th scope="col" className="px-4 py-3 font-medium">{copy.bestProduct}</th>
                  <th scope="col" className="px-4 py-3 text-center font-medium">{copy.itemsSold}</th>
                  <th scope="col" className="px-4 py-3 text-center font-medium">{copy.gmv}</th>
                </tr>
              </thead>
              <tbody>
                {creators.map((creator, index) => {
                  const rank = (page - 1) * pageSize + index + 1;
                  const bestProduct = creator.products[0] ?? null;
                  const creatorName = creator.displayName ?? creator.handle ?? creator.id;
                  return (
                    <tr key={creator.id} className="border-b border-border last:border-0 hover:bg-secondary/30">
                      <td className="px-4 py-3">
                        <RankBadge rank={rank} />
                      </td>
                      <td className="px-4 py-3">
                        <Link href={`/dashboard/creators/${creator.id}`} className="flex min-w-0 items-center gap-3">
                          <StoreAvatar name={creatorName} avatarUrl={creator.avatarUrl} size="lg" />
                          <span className="flex min-w-0 flex-col gap-0.5">
                            <strong className="truncate text-[13px] font-bold text-foreground">{creatorName}</strong>
                            <small className="truncate text-[11px] text-muted-foreground">{creator.handle ? `@${creator.handle}` : "Handle unavailable"}</small>
                          </span>
                        </Link>
                      </td>
                      <td className="px-4 py-3">
                        {bestProduct ? (
                          <Link href={`/dashboard/products/${bestProduct.id}`} className="flex min-w-0 items-center gap-2.5 text-[11.5px] text-foreground hover:text-primary">
                            <ProductImage
                              src={bestProduct.imageUrl}
                              alt={bestProduct.canonicalName}
                              className="size-11 shrink-0 rounded-lg border"
                              sizes="44px"
                              fit="contain"
                            />
                            <span className="truncate">{bestProduct.canonicalName}</span>
                          </Link>
                        ) : (
                          <span className="text-xs text-muted-foreground">{copy.unavailable}</span>
                        )}
                      </td>
                      <td className="px-4 py-3 text-center tabular-nums text-foreground">
                        {formatUnits(bestProduct?.unitsSold ?? null, locale, copy.unavailable)}
                      </td>
                      <td className="px-4 py-3 text-center tabular-nums text-foreground">
                        {formatMoney(bestProduct?.gmv ?? null, bestProduct?.currency ?? null, locale, copy.unavailable)}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </Card>

      {!loadError && creators.length > 0 && (
        <div className="flex items-center justify-center gap-3">
          <Button
            variant="outline"
            size="sm"
            disabled={page <= 1 || isPending}
            onClick={() => navigate({ page: String(page - 1) })}
          >
            <ChevronLeft className="size-4" />
            {copy.previous}
          </Button>
          <span className="text-sm text-muted-foreground">
            {copy.pageOf.replace("{page}", String(page)).replace("{total}", String(totalPages))}
          </span>
          <Button
            variant="outline"
            size="sm"
            disabled={page >= totalPages || isPending}
            onClick={() => navigate({ page: String(page + 1) })}
          >
            {copy.next}
            <ChevronRight className="size-4" />
          </Button>
        </div>
      )}
    </div>
  );
}

const RANK_MEDAL_CLASSES: Record<number, string> = {
  1: "bg-amber-400/15 text-amber-600 dark:text-amber-400",
  2: "bg-slate-400/15 text-slate-600 dark:text-slate-300",
  3: "bg-orange-400/15 text-orange-600 dark:text-orange-400",
};

function RankBadge({ rank }: { rank: number }) {
  return (
    <span
      className={cn(
        "flex size-7 items-center justify-center rounded-full text-xs font-bold",
        RANK_MEDAL_CLASSES[rank] ?? "text-muted-foreground",
      )}
      aria-label={`Rank ${rank}`}
    >
      {rank <= 3 ? <Medal className="size-3.5" aria-hidden="true" /> : rank}
    </span>
  );
}
