"use client";

import * as React from "react";
import { EyeIcon, PlusIcon, UserIcon } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { EmptyState } from "@/components/ui/empty-state";
import { Typography } from "@/components/ui/typography";
import { DataTable, useDataTableQuery } from "@/components/data-table";
import type { DataTableColumn } from "@/components/data-table";
import { useAdminCustomers } from "@/hooks/customers/useAdminCustomers";
import { useTranslation } from "@/hooks/useTranslation";
import type { WashCustomers } from "@/types/customers";

import { CustomerDetailsDialog } from "./WashCustomerDetailsDialog";

export function CustomersView() {
  const { t } = useTranslation();
  const { query, setQuery } = useDataTableQuery();
  const [detailsTarget, setDetailsTarget] =
    React.useState<WashCustomers | null>(null);

  const { data, isLoading, isError, refetch } = useAdminCustomers({
    search: query.search,
    page: query.page,
    limit: query.pageSize,
  });

  const columns = React.useMemo<DataTableColumn<WashCustomers>[]>(
    () => [
      {
        // First column doubles as the mobile card title — keep it identifying.
        key: "name",
        header: t("customers.columns.name"),
        cell: (pkg) => (
          <div className="flex min-w-0 items-center gap-2">
            <span className="flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-information-light text-primary-sky-blue">
              <UserIcon className="size-4" />
            </span>
            <div className="flex min-w-0 flex-col gap-1">
              <Typography as="span" variant="body" className="truncate">
                {pkg?.firstName} {pkg?.lastName}
              </Typography>
            </div>
          </div>
        ),
      },
      {
        key: "email",
        header: t("customers.columns.email"),
        cell: (pkg) => (
          <Typography as="span" variant="number">
            {pkg.email}
          </Typography>
        ),
      },
      {
        key: "phone",
        header: t("customers.columns.phone"),
        hideOnMobile: true,
        // Capped: a package with six features would otherwise stretch the table
        // past its container and force a horizontal scroll for one text cell.
        // The full list is one click away in the edit dialog.
        className: "max-w-[320px]",
        cell: (pkg) => (
          <Typography
            as="p"
            variant="caption"
            color="secondary"
            className="truncate"
          >
            {pkg.phoneNumber}
          </Typography>
        ),
      },
      {
        key: "status",
        header: t("customers.columns.status"),
        cell: (pkg) => (
          <Badge variant={pkg.isActive ? "complete" : "closed"}>
            {pkg.isActive
              ? t("customers.status.active")
              : t("customers.status.inactive")}
          </Badge>
        ),
      },
    ],
    [t],
  );

  return (
    <div className="flex flex-col gap-6">
      {/* py-1 keeps the active pill's shadow from being clipped by the
          scroll container (setting overflow-x also computes overflow-y). */}

      <DataTable
        mode="server"
        columns={columns}
        data={data?.data ?? []}
        totalCount={data?.total ?? 0}
        getRowId={(pkg) => pkg.id}
        query={query}
        onQueryChange={setQuery}
        searchable
        searchPlaceholder={t("customers.searchPlaceholder")}
        loading={isLoading}
        error={isError}
        onRetry={() => refetch()}
        rowActions={(pkg) => [
          {
            key: "view",
            label: t("customers.actions.view"),
            icon: <EyeIcon />,
            onSelect: () => setDetailsTarget(pkg),
          },
        ]}
        // Only override the empty state for a genuinely empty catalog. With a
        // search active the DataTable's own "no results" copy is the correct
        // message, so leave it undefined and let it win.
        emptyState={
          !query.search.trim() ? (
            <EmptyState
              icon={<UserIcon />}
              title={t("catalog.emptyTitle")}
              description={t("catalog.emptyDescription")}
              action={
                <Button className="w-full">
                  <PlusIcon />
                  {t("catalog.actions.new")}
                </Button>
              }
            />
          ) : undefined
        }
      />

      <CustomerDetailsDialog
        target={detailsTarget}
        onClose={() => setDetailsTarget(null)}
      />
    </div>
  );
}
