"use client";

import { useMemo } from "react";
import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import { ArrowUpRight, Store } from "lucide-react";
import { PageHeader } from "@/components/shared/page-header";
import { DebouncedSearch } from "@/components/shared/debounced-search";
import { Pagination } from "@/components/shared/pagination";
import { EmptyState, ErrorState, TableSkeleton } from "@/components/shared/states";
import { StoreStatusBadge } from "@/components/shared/store-badges";
import { Card } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  getStoreClients,
  STORE_CLIENT_STATUSES,
  type StoreClientFilters,
} from "@/services/store-clients";
import { queryKeys } from "@/lib/query-keys";
import { useUrlState } from "@/lib/use-url-state";
import { useI18n, useT } from "@/i18n";
import { formatDateTime, truncate } from "@/lib/format";
import { friendlyErrorMessage } from "@/lib/errors";
import type { StoreClientStatus } from "@/types/store";

/**
 * The shops that feed us orders.
 *
 * The review queue and the directory are the same screen, filtered — a separate "applications"
 * page would split a store's history across two places the moment it was approved.
 */
export default function StoresPage() {
  const t = useT();
  const { locale } = useI18n();

  const [page, setPage] = useUrlState("page", 1, (value) => {
    const n = Number(value);
    return Number.isFinite(n) && n >= 1 ? n : null;
  });
  const [status, setStatus] = useUrlState<StoreClientStatus | "">("status", "", (value) =>
    (STORE_CLIENT_STATUSES as string[]).includes(value) ? (value as StoreClientStatus) : null,
  );
  const [search, setSearch] = useUrlState("search", "", (value) => value);

  const filters = useMemo<StoreClientFilters>(
    () => ({ page, rows: 10, search: search || undefined, status: status || undefined }),
    [page, search, status],
  );

  const { data, isLoading, isError, error, refetch } = useQuery({
    queryKey: queryKeys.storeClients.list(filters),
    queryFn: () => getStoreClients(filters),
  });

  const stores = data?.Model ?? [];

  return (
    <div>
      <PageHeader title={t("stores.title")} subtitle={t("stores.subtitle")} />

      <Card>
        <div className="flex flex-col gap-3 border-b p-4 sm:flex-row sm:items-center">
          <DebouncedSearch
            value={search}
            onChange={(value) => {
              setPage(1);
              setSearch(value);
            }}
            placeholder={t("stores.searchPlaceholder")}
            className="w-full sm:max-w-xs"
          />
          <div className="ms-auto flex items-center gap-2">
            <span className="text-xs text-muted-foreground">{t("stores.filterStatus")}</span>
            <Select
              value={status || "all"}
              onValueChange={(value) => {
                setPage(1);
                setStatus(value === "all" ? "" : (value as StoreClientStatus));
              }}
            >
              <SelectTrigger className="w-[10.5rem]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">{t("common.all")}</SelectItem>
                {STORE_CLIENT_STATUSES.map((option) => (
                  <SelectItem key={option} value={option}>
                    {t(`stores.status.${option}`)}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        {isLoading ? (
          <TableSkeleton rows={8} cols={6} />
        ) : isError ? (
          <ErrorState message={friendlyErrorMessage(error, t)} onRetry={() => refetch()} />
        ) : stores.length === 0 ? (
          <EmptyState
            title={t("stores.empty")}
            description={t("stores.emptyHint")}
            icon={Store}
          />
        ) : (
          <>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{t("stores.title")}</TableHead>
                    <TableHead>{t("stores.handle")}</TableHead>
                    <TableHead>{t("stores.callbackUrl")}</TableHead>
                    <TableHead>{t("common.status")}</TableHead>
                    <TableHead>{t("common.createdAt")}</TableHead>
                    <TableHead aria-label={t("common.actions")} />
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {stores.map((store) => (
                    <TableRow key={store.uuid}>
                      <TableCell className="font-semibold text-foreground">{store.name}</TableCell>
                      <TableCell className="text-xs text-muted-foreground">{store.slug}</TableCell>
                      <TableCell className="max-w-[18rem] text-xs text-muted-foreground">
                        {store.webhook_url ? (
                          truncate(store.webhook_url, 46)
                        ) : (
                          <span className="italic">{t("stores.noCallbackUrl")}</span>
                        )}
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <StoreStatusBadge status={store.status} label={store.status_label} />
                          {/*
                            Approved and paused are different things, and the status alone cannot
                            say which. A store reading "approved" while nothing flows is exactly
                            the confusion this second mark exists to prevent.
                          */}
                          {store.status === "approved" && !store.is_live ? (
                            <span className="text-[0.7rem] text-muted-foreground">
                              {t("stores.notLive")}
                            </span>
                          ) : null}
                        </div>
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {formatDateTime(store.created_at, locale)}
                      </TableCell>
                      <TableCell>
                        <Link
                          href={`/stores/${store.uuid}`}
                          className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"
                        >
                          {t("common.view")}
                          <ArrowUpRight className="h-3 w-3" aria-hidden />
                        </Link>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
            <Pagination
              page={data!.Page}
              totalPages={data!.Total}
              records={data!.Records}
              onPageChange={(next) => setPage(next)}
            />
          </>
        )}
      </Card>
    </div>
  );
}
