"use client";

import { use } from "react";
import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import { ArrowLeft, Package } from "lucide-react";
import { PageHeader } from "@/components/shared/page-header";
import { ErrorState } from "@/components/shared/states";
import { StoreStatusBadge } from "@/components/shared/store-badges";
import { Card } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { StoreConfiguration } from "@/features/stores/store-configuration";
import { StoreCredentials } from "@/features/stores/store-credentials";
import { StorePeople } from "@/features/stores/store-people";
import { StoreReviewActions } from "@/features/stores/store-review-actions";
import { StoreSettlements } from "@/features/stores/store-settlements";
import { useI18n, useT } from "@/i18n";
import { useCan } from "@/features/auth/use-can";
import { formatDateTime } from "@/lib/format";
import { friendlyErrorMessage } from "@/lib/errors";
import { queryKeys } from "@/lib/query-keys";
import { getStoreClient } from "@/services/store-clients";

/**
 * One store: the decision on it, its configuration, its people and its money.
 *
 * The header carries the thing most easily misread — a store can be **approved and not trading**
 * at the same time, because approval and the operational pause are separate switches. A status
 * chip alone would let somebody stare at "Approved" while wondering why no orders arrive.
 */
export default function StoreDetailPage({ params }: { params: Promise<{ uuid: string }> }) {
  const { uuid } = use(params);
  const t = useT();
  const { locale } = useI18n();
  const { can } = useCan();

  const { data, isLoading, isError, error, refetch } = useQuery({
    queryKey: queryKeys.storeClients.detail(uuid),
    queryFn: () => getStoreClient(uuid),
  });

  const store = data?.Model ?? null;

  if (isLoading) {
    return (
      <div className="space-y-4">
        <Skeleton className="h-10 w-64" />
        <Skeleton className="h-48 w-full" />
      </div>
    );
  }

  if (isError || !store) {
    return <ErrorState message={friendlyErrorMessage(error, t)} onRetry={() => refetch()} />;
  }

  return (
    <div>
      <Link
        href="/stores"
        className="mb-3 inline-flex items-center gap-1 text-xs font-medium text-muted-foreground hover:text-foreground"
      >
        <ArrowLeft className="h-3 w-3" aria-hidden />
        {t("stores.title")}
      </Link>

      <PageHeader
        title={store.name}
        subtitle={store.slug}
        actions={<StoreReviewActions store={store} />}
      />

      <Card className="mb-4 p-5">
        <div className="flex flex-wrap items-center gap-3">
          <StoreStatusBadge status={store.status} label={store.status_label} />

          {/*
            Approved and trading are not the same thing. Saying so here costs one line and saves
            the "why is nothing arriving?" conversation.
          */}
          <span
            className={
              store.is_live
                ? "text-xs font-medium text-success"
                : "text-xs font-medium text-muted-foreground"
            }
          >
            {store.is_live ? t("stores.live") : t("stores.notLive")}
          </span>

          {can("orders.view") ? (
            <Link
              href={`/orders?store_client_uuid=${store.uuid}`}
              className="ms-auto inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"
            >
              <Package className="h-3 w-3" aria-hidden />
              {t("orders.title")}
            </Link>
          ) : null}
        </div>

        {store.review_note ? (
          <div className="mt-4 rounded-md bg-muted/50 p-3">
            <p className="text-xs font-medium text-foreground">{t("stores.reviewNote")}</p>
            <p className="mt-1 text-sm text-muted-foreground">{store.review_note}</p>
            {store.reviewed_at ? (
              <p className="mt-1 text-[0.7rem] text-muted-foreground">
                {t("stores.reviewedAt")}: {formatDateTime(store.reviewed_at, locale)}
              </p>
            ) : null}
          </div>
        ) : null}
      </Card>

      <Tabs defaultValue="overview">
        <TabsList>
          <TabsTrigger value="overview">{t("stores.tab.overview")}</TabsTrigger>
          <TabsTrigger value="people">{t("stores.tab.people")}</TabsTrigger>
          {can(["settlements.view", "settlements.manage"]) ? (
            <TabsTrigger value="settlements">{t("stores.tab.settlements")}</TabsTrigger>
          ) : null}
        </TabsList>

        <TabsContent value="overview" className="space-y-4 pt-4">
          <StoreConfiguration store={store} />
          <StoreCredentials store={store} />
        </TabsContent>

        <TabsContent value="people" className="pt-4">
          <StorePeople store={store} />
        </TabsContent>

        {can(["settlements.view", "settlements.manage"]) ? (
          <TabsContent value="settlements" className="pt-4">
            <StoreSettlements store={store} />
          </TabsContent>
        ) : null}
      </Tabs>
    </div>
  );
}
