"use client";

import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import {
  ChevronDown,
  ChevronUp,
  Download,
  Info,
  MoreVertical,
  Plus,
  Search,
  SlidersHorizontal,
  X,
} from "lucide-react";
import { toast } from "react-hot-toast";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { FormField, SelectField } from "@/components/shared/form-field";
import { exportData, type ExportFormat, type ExportRow } from "@/lib/export-data";
import { updateQuery } from "@/lib/list-query";
import { submitCustomer } from "./client-api";
import type { CustomerApiPage } from "./api-contract";
import { customerPageSizes, type CustomerListQuery } from "./customer-query";
import type {
  CreateCustomerValues,
  CustomerFilters,
  CustomerRecord,
  CustomerSortKey,
} from "./types";

const emptyFilters: CustomerFilters = {
  organizationCode: "",
  firstName: "",
  lastName: "",
  email: "",
  phone: "",
  active: "",
};
const filterLabels: Record<keyof CustomerFilters, string> = {
  organizationCode: "Organization Code",
  firstName: "First Name",
  lastName: "Last Name",
  email: "Email",
  phone: "Phone",
  active: "Status",
};

function emptyCreateCustomer(): CreateCustomerValues {
  return {
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
    active: true,
    address: {
      streetAndNumber: "",
      city: "",
      postalCode: "",
      state: "",
      country: "",
    },
    basicInformation: {
      avatarUrl: "",
      dateOfBirth: "",
      placeOfBirth: "",
      gender: "",
    },
  };
}

function formatDate(value: string) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "—";
  return new Intl.DateTimeFormat("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    timeZone: "UTC",
  }).format(date);
}

function fullName(customer: CustomerRecord) {
  return `${customer.firstName} ${customer.lastName}`.trim();
}

function toExportRow(customer: CustomerRecord): ExportRow {
  return {
    Name: fullName(customer),
    Email: customer.email,
    Phone: customer.phone,
    Roles: customer.roles.join(", "),
    Status: customer.active ? "Active" : "Inactive",
    "Created At": formatDate(customer.createdAt),
  };
}

export function CustomerView({
  initialCustomers,
  pagination,
  query,
  canManage = true,
  loadError,
}: {
  initialCustomers: CustomerRecord[];
  pagination: CustomerApiPage["pagination"];
  query: CustomerListQuery;
  canManage?: boolean;
  loadError?: string;
}) {
  const customers = initialCustomers;
  const router = useRouter();
  const pathname = usePathname();
  const params = useSearchParams();
  const urlSearch = params.get("search") ?? "";
  const [search, setSearch] = useState(query.search);
  const [filterDraft, setFilterDraft] = useState<CustomerFilters>(query.filters);
  const [filterOpen, setFilterOpen] = useState(false);
  const [downloadOpen, setDownloadOpen] = useState(false);
  const [downloadFormat, setDownloadFormat] = useState<ExportFormat>("csv");
  const [downloadScope, setDownloadScope] = useState<"page" | "filtered">("page");
  const [downloadError, setDownloadError] = useState("");
  const [downloading, setDownloading] = useState(false);
  const [createOpen, setCreateOpen] = useState(false);
  const [createDraft, setCreateDraft] = useState<CreateCustomerValues>(emptyCreateCustomer);
  const [creating, setCreating] = useState(false);

  const updateListQuery = useCallback((updates: Record<string, string | null>) => {
    const next = updateQuery(params.toString(), updates);
    router.replace(next ? `${pathname}?${next}` : pathname, { scroll: false });
  }, [params, pathname, router]);

  useEffect(() => {
    setSearch(query.search);
    setFilterDraft(query.filters);
  }, [query.search, query.filters]);

  useEffect(() => {
    if (search.trim() === urlSearch) return;
    const timeout = window.setTimeout(() => {
      updateListQuery({ search: search.trim() || null, paginate_page: "1" });
    }, 350);
    return () => window.clearTimeout(timeout);
  }, [search, urlSearch, updateListQuery]);

  const visibleCustomers = useMemo(() => {
    if (query.sortKey !== "phone" && query.sortKey !== "active") return customers;
    return [...customers].sort((left, right) => {
      const comparison = query.sortKey === "active"
        ? Number(left.active) - Number(right.active)
        : left.phone.localeCompare(right.phone, undefined, { numeric: true });
      return query.sortOrder === "asc" ? comparison : -comparison;
    });
  }, [customers, query.sortKey, query.sortOrder]);

  const totalPages = Math.max(1, pagination.totalPages);
  const startIndex = pagination.totalDocs ? pagination.pagingCounter : 0;
  const endIndex = pagination.totalDocs
    ? Math.min(startIndex + visibleCustomers.length - 1, pagination.totalDocs)
    : 0;
  const activeFilters = (Object.entries(query.filters) as [keyof CustomerFilters, string][])
    .filter(([, value]) => value !== "");
  const firstPageNumber = Math.max(1, Math.min(pagination.page - 2, totalPages - 4));
  const pageNumbers = Array.from(
    { length: Math.min(totalPages, 5) },
    (_, index) => firstPageNumber + index,
  );

  function changeSort(key: CustomerSortKey) {
    const order = query.sortKey === key && query.sortOrder === "asc" ? "desc" : "asc";
    updateListQuery({
      sort_by: key === "firstName" ? "firstname" : key,
      sort_order: order,
      paginate_page: "1",
    });
  }

  function removeFilter(key: keyof CustomerFilters) {
    const queryKey: Record<keyof CustomerFilters, string> = {
      organizationCode: "organization_code",
      firstName: "firstname",
      lastName: "lastname",
      email: "email",
      phone: "phone",
      active: "active",
    };
    updateListQuery({ [queryKey[key]]: null, paginate_page: "1" });
  }

  function resetFilters() {
    setFilterDraft({ ...emptyFilters });
    updateListQuery({
      organization_code: null,
      firstname: null,
      lastname: null,
      email: null,
      phone: null,
      active: null,
      paginate_page: "1",
    });
    setFilterOpen(false);
  }

  async function downloadCustomers() {
    if (search.trim() !== urlSearch) {
      setDownloadError("Wait for the search results to update before exporting.");
      return;
    }
    if (downloadScope === "page" && !visibleCustomers.length) return;
    if (downloadScope === "filtered" && !pagination.totalDocs) return;
    setDownloading(true);
    setDownloadError("");
    try {
      let data = visibleCustomers;
      if (downloadScope === "filtered") {
        const exportQuery = new URLSearchParams(params.toString());
        exportQuery.delete("paginate_page");
        exportQuery.delete("paginate_limit");
        const response = await fetch(`/api/customers/export?${exportQuery.toString()}`, {
          cache: "no-store",
        });
        const result: unknown = await response.json().catch(() => null);
        if (!response.ok || !result || typeof result !== "object" || !("customers" in result) || !Array.isArray(result.customers)) {
          const message = result && typeof result === "object" && "error" in result && typeof result.error === "string"
            ? result.error
            : "Unable to prepare this download. Please try again.";
          throw new Error(message);
        }
        data = result.customers as CustomerRecord[];
      }
      await exportData("Customers", data.map(toExportRow), downloadFormat);
      setDownloadOpen(false);
    } catch (error) {
      setDownloadError(error instanceof Error ? error.message : "Unable to prepare this download. Please try again.");
    } finally {
      setDownloading(false);
    }
  }

  function openCreateCustomer() {
    setCreateDraft(emptyCreateCustomer());
    setCreateOpen(true);
  }

  async function handleCreateCustomer(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setCreating(true);
    try {
      const message = await submitCustomer(createDraft);
      setCreateOpen(false);
      setCreateDraft(emptyCreateCustomer());
      toast.success(message || "Customer created successfully.");
      const next = updateQuery(params.toString(), { paginate_page: "1" });
      if (next !== params.toString()) {
        router.replace(next ? `${pathname}?${next}` : pathname, { scroll: false });
      } else {
        router.refresh();
      }
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Unable to create the customer. Please try again.");
    } finally {
      setCreating(false);
    }
  }

  return (
    <section className="overflow-hidden rounded-2xl border border-border bg-card">
      <header className="px-6 py-5">
        <h2 className="text-base font-medium">Customer List</h2>
      </header>

      <div className="border-t border-border p-4 sm:p-6">
        {loadError && (
          <p role="alert" className="mb-5 rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
            {loadError}
          </p>
        )}
        <div className="space-y-6">
          {activeFilters.length > 0 && (
            <div className="flex flex-wrap items-center gap-2 rounded-lg border border-border bg-muted/40 px-4 py-3">
              <span className="text-sm text-muted-foreground">
                {activeFilters.length} filter{activeFilters.length === 1 ? "" : "s"} applied:
              </span>
              {activeFilters.map(([key, value]) => (
                <span key={key} className="inline-flex items-center gap-1 rounded-full border border-border bg-background px-2.5 py-1 text-xs">
                  {key === "active" ? `Status: ${value === "true" ? "Active" : "Inactive"}` : `${filterLabels[key]}: ${value}`}
                  <button
                    type="button"
                    aria-label={`Remove ${filterLabels[key]} filter`}
                    className="rounded-full text-muted-foreground hover:text-foreground"
                    onClick={() => removeFilter(key)}
                  >
                    <X className="size-3" />
                  </button>
                </span>
              ))}
              <button type="button" className="ml-1 text-sm font-medium text-destructive hover:underline" onClick={resetFilters}>
                Clear all filters
              </button>
            </div>
          )}

          <div className="flex flex-col gap-3 border border-b-0 border-border px-4 py-4 sm:flex-row sm:items-center sm:justify-between">
            <label className="flex items-center gap-3 text-sm text-muted-foreground">
              <span>Show</span>
              <select
                aria-label="Show entries"
                value={query.limit}
                onChange={(event) => {
                  updateListQuery({ paginate_limit: event.target.value, paginate_page: "1" });
                }}
                className="h-9 rounded-lg border border-input bg-background px-3 text-sm text-foreground outline-none focus:border-primary"
              >
                {customerPageSizes.map((size) => <option key={size} value={size}>{size}</option>)}
              </select>
              <span>entries</span>
            </label>

            <div className="flex flex-wrap items-center gap-2">
              {canManage && (
                <Button type="button" size="sm" onClick={openCreateCustomer}>
                  <Plus aria-hidden="true" />
                  Add Customer
                </Button>
              )}
              <Button type="button" variant="outline" size="sm" onClick={() => {
                setFilterDraft({ ...query.filters });
                setFilterOpen(true);
              }}>
                <SlidersHorizontal aria-hidden="true" />
                Filter
              </Button>
              <Button type="button" variant="outline" size="sm" onClick={() => {
                setDownloadError("");
                setDownloadOpen(true);
              }}>
                <Download aria-hidden="true" />
                Download
              </Button>
              <label className="relative min-w-0 flex-1 sm:w-[250px] sm:flex-none">
                <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" aria-hidden="true" />
                <Input
                  type="search"
                  aria-label="Search customers"
                  value={search}
                  onChange={(event) => setSearch(event.target.value)}
                  placeholder="Search..."
                  className="h-11 pl-10"
                />
              </label>
            </div>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full min-w-[800px] border-collapse text-left">
              <caption className="sr-only">Customer list</caption>
              <thead className="border-t border-border bg-muted/20">
                <tr>
                  {([
                    ["firstName", "Name"],
                    ["email", "Email"],
                    ["phone", "Phone"],
                    ["active", "Status"],
                  ] as const).map(([key, label]) => (
                    <th key={key} className="border border-border px-4 py-3 text-xs font-medium text-muted-foreground">
                      <button
                        type="button"
                        className="flex w-full items-center justify-between gap-3 whitespace-nowrap"
                        aria-label={`Sort by ${label}`}
                        aria-sort={query.sortKey === key ? (query.sortOrder === "asc" ? "ascending" : "descending") : "none"}
                        onClick={() => changeSort(key)}
                      >
                        <span>{label}</span>
                        <span className="flex flex-col">
                          <ChevronUp className={`size-3 ${query.sortKey === key && query.sortOrder === "asc" ? "text-primary" : "opacity-40"}`} />
                          <ChevronDown className={`size-3 ${query.sortKey === key && query.sortOrder === "desc" ? "text-primary" : "opacity-40"}`} />
                        </span>
                      </button>
                    </th>
                  ))}
                  <th className="border border-border px-4 py-3 text-xs font-medium text-muted-foreground">Actions</th>
                </tr>
              </thead>
              <tbody>
                {visibleCustomers.map((customer) => (
                  <tr key={customer.id} className="hover:bg-muted/20">
                    <td className="whitespace-nowrap border border-border px-4 py-4 text-sm font-medium">
                      <Link href={`/customers/${encodeURIComponent(customer.id)}`} className="text-foreground hover:text-success hover:underline">
                        {fullName(customer)}
                      </Link>
                    </td>
                    <td className="whitespace-nowrap border border-border px-4 py-4 text-sm">{customer.email}</td>
                    <td className="whitespace-nowrap border border-border px-4 py-4 text-sm">{customer.phone || "—"}</td>
                    <td className="whitespace-nowrap border border-border px-4 py-4 text-sm">
                      <div className="flex items-center gap-2">
                        <button
                          type="button"
                          role="switch"
                          aria-checked={customer.active}
                          aria-label={`${fullName(customer)} status`}
                          aria-disabled="true"
                          disabled
                          title="Status is read-only until an update endpoint is connected."
                          className={`relative inline-flex h-6 w-11 cursor-not-allowed items-center rounded-full opacity-75 ${customer.active ? "bg-success" : "bg-input"}`}
                        >
                          <span className={`inline-block size-4 rounded-full bg-background shadow transition-transform ${customer.active ? "translate-x-6" : "translate-x-1"}`} />
                        </button>
                        <span className="text-xs text-muted-foreground">{customer.active ? "Active" : "Inactive"}</span>
                      </div>
                    </td>
                    <td className="whitespace-nowrap border border-border px-4 py-4 text-sm">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button type="button" variant="ghost" size="icon-sm" aria-label={`Actions for ${fullName(customer)}`}>
                            <MoreVertical className="size-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="w-52">
                          <DropdownMenuItem onSelect={() => router.push(`/customers/${encodeURIComponent(customer.id)}`)}>
                            <Info />
                            View customer details
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </td>
                  </tr>
                ))}
                {visibleCustomers.length === 0 && (
                  <tr>
                    <td colSpan={5} className="h-40 border border-border px-4 text-center text-sm text-muted-foreground">
                      {loadError
                        ? "Unable to display customers."
                        : query.search || activeFilters.length
                          ? "No customers match your search or filters."
                          : "No customers found."}
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          <div className="flex flex-col gap-4 border border-t-0 border-border px-4 py-4 sm:flex-row sm:items-center sm:justify-between">
            <p className="text-center text-sm text-muted-foreground sm:text-left">
              Showing {startIndex} to {endIndex} of {pagination.totalDocs} entries
            </p>
            <nav aria-label="Pagination" className="flex flex-wrap items-center justify-center gap-1 sm:justify-end">
              <Button type="button" variant="outline" size="xs" disabled={pagination.page <= 1} onClick={() => updateListQuery({ paginate_page: String(pagination.page - 1) })}>Previous</Button>
              {pageNumbers.map((number) => (
                <button
                  key={number}
                  type="button"
                  aria-label={`Go to page ${number}`}
                  aria-current={pagination.page === number ? "page" : undefined}
                  className={`size-8 rounded-lg text-sm ${pagination.page === number ? "bg-primary text-primary-foreground" : "hover:bg-muted"}`}
                  onClick={() => updateListQuery({ paginate_page: String(number) })}
                >
                  {number}
                </button>
              ))}
              <Button type="button" variant="outline" size="xs" disabled={!pagination.hasNextPage} onClick={() => updateListQuery({ paginate_page: String(pagination.page + 1) })}>Next</Button>
            </nav>
          </div>
        </div>
      </div>

      {canManage && <Dialog open={createOpen} onOpenChange={(open) => {
        if (!creating) setCreateOpen(open);
      }}>
        <DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-3xl">
          <DialogHeader>
            <DialogTitle>Add Customer</DialogTitle>
            <DialogDescription>
              Create an EV driver account. Tenant is taken from your session and the role is set to user.
            </DialogDescription>
          </DialogHeader>
          <form className="space-y-5" onSubmit={handleCreateCustomer}>
            <div className="grid gap-4 sm:grid-cols-2">
              <FormField
                label="First Name"
                name="customerFirstName"
                autoComplete="given-name"
                required
                maxLength={100}
                value={createDraft.firstName}
                onChange={(event) => setCreateDraft((current) => ({ ...current, firstName: event.target.value }))}
              />
              <FormField
                label="Last Name"
                name="customerLastName"
                autoComplete="family-name"
                required
                maxLength={100}
                value={createDraft.lastName}
                onChange={(event) => setCreateDraft((current) => ({ ...current, lastName: event.target.value }))}
              />
              <FormField
                label="Email"
                name="customerEmail"
                type="email"
                autoComplete="email"
                required
                maxLength={254}
                value={createDraft.email}
                onChange={(event) => setCreateDraft((current) => ({ ...current, email: event.target.value }))}
              />
              <FormField
                label="Phone"
                name="customerPhone"
                type="tel"
                autoComplete="tel"
                required
                maxLength={40}
                value={createDraft.phone}
                onChange={(event) => setCreateDraft((current) => ({ ...current, phone: event.target.value }))}
              />
            </div>

            <label className="flex items-center gap-2 text-sm">
              <input
                type="checkbox"
                checked={createDraft.active}
                onChange={(event) => setCreateDraft((current) => ({ ...current, active: event.target.checked }))}
                className="size-4 accent-primary"
              />
              Active account
            </label>

            <details className="rounded-lg border border-border px-4 py-3">
              <summary className="cursor-pointer text-sm font-medium">Optional profile details</summary>
              <div className="mt-4 grid gap-4 sm:grid-cols-2">
                <FormField
                  label="Street and Number"
                  name="customerStreetAndNumber"
                  autoComplete="street-address"
                  maxLength={200}
                  value={createDraft.address.streetAndNumber}
                  onChange={(event) => setCreateDraft((current) => ({ ...current, address: { ...current.address, streetAndNumber: event.target.value } }))}
                />
                <FormField
                  label="City"
                  name="customerCity"
                  autoComplete="address-level2"
                  maxLength={200}
                  value={createDraft.address.city}
                  onChange={(event) => setCreateDraft((current) => ({ ...current, address: { ...current.address, city: event.target.value } }))}
                />
                <FormField
                  label="Postal Code"
                  name="customerPostalCode"
                  autoComplete="postal-code"
                  maxLength={200}
                  value={createDraft.address.postalCode}
                  onChange={(event) => setCreateDraft((current) => ({ ...current, address: { ...current.address, postalCode: event.target.value } }))}
                />
                <FormField
                  label="State or Province"
                  name="customerState"
                  autoComplete="address-level1"
                  maxLength={200}
                  value={createDraft.address.state}
                  onChange={(event) => setCreateDraft((current) => ({ ...current, address: { ...current.address, state: event.target.value } }))}
                />
                <FormField
                  label="Country"
                  name="customerCountry"
                  autoComplete="country-name"
                  maxLength={200}
                  value={createDraft.address.country}
                  onChange={(event) => setCreateDraft((current) => ({ ...current, address: { ...current.address, country: event.target.value } }))}
                />
                <FormField
                  label="Avatar URL"
                  name="customerAvatarUrl"
                  type="url"
                  maxLength={2048}
                  value={createDraft.basicInformation.avatarUrl}
                  onChange={(event) => setCreateDraft((current) => ({ ...current, basicInformation: { ...current.basicInformation, avatarUrl: event.target.value } }))}
                />
                <FormField
                  label="Date of Birth"
                  name="customerDateOfBirth"
                  type="date"
                  value={createDraft.basicInformation.dateOfBirth}
                  onChange={(event) => setCreateDraft((current) => ({ ...current, basicInformation: { ...current.basicInformation, dateOfBirth: event.target.value } }))}
                />
                <FormField
                  label="Place of Birth"
                  name="customerPlaceOfBirth"
                  maxLength={200}
                  value={createDraft.basicInformation.placeOfBirth}
                  onChange={(event) => setCreateDraft((current) => ({ ...current, basicInformation: { ...current.basicInformation, placeOfBirth: event.target.value } }))}
                />
                <FormField
                  label="Gender"
                  name="customerGender"
                  maxLength={50}
                  value={createDraft.basicInformation.gender}
                  onChange={(event) => setCreateDraft((current) => ({ ...current, basicInformation: { ...current.basicInformation, gender: event.target.value } }))}
                />
              </div>
            </details>

            <DialogFooter>
              <Button type="button" variant="outline" disabled={creating} onClick={() => setCreateOpen(false)}>
                Cancel
              </Button>
              <Button type="submit" disabled={creating}>
                {creating ? "Creating..." : "Create Customer"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>}

      <Dialog open={filterOpen} onOpenChange={setFilterOpen}>
        <DialogContent className="sm:max-w-3xl">
          <DialogHeader>
            <DialogTitle>Filter Customers</DialogTitle>
            <DialogDescription>Apply filters to narrow down the customer list.</DialogDescription>
          </DialogHeader>
          <div className="grid max-h-[65vh] gap-5 overflow-y-auto pr-1 sm:grid-cols-2">
            <FormField label="Organization Code" name="filterOrganizationCode" value={filterDraft.organizationCode} onChange={(event) => setFilterDraft((current) => ({ ...current, organizationCode: event.target.value }))} placeholder="Filter by organization code" />
            <FormField label="First Name" name="filterFirstName" value={filterDraft.firstName} onChange={(event) => setFilterDraft((current) => ({ ...current, firstName: event.target.value }))} placeholder="Filter by First Name" />
            <FormField label="Last Name" name="filterLastName" value={filterDraft.lastName} onChange={(event) => setFilterDraft((current) => ({ ...current, lastName: event.target.value }))} placeholder="Filter by Last Name" />
            <FormField label="Email" name="filterEmail" type="email" value={filterDraft.email} onChange={(event) => setFilterDraft((current) => ({ ...current, email: event.target.value }))} placeholder="Filter by Email" />
            <FormField label="Phone" name="filterPhone" type="tel" value={filterDraft.phone} onChange={(event) => setFilterDraft((current) => ({ ...current, phone: event.target.value }))} placeholder="Filter by Phone" />
            <SelectField
              label="Status"
              name="filterActive"
              value={filterDraft.active}
              onChange={(event) => setFilterDraft((current) => ({ ...current, active: event.target.value as CustomerFilters["active"] }))}
              options={[
                { value: "", label: "All" },
                { value: "true", label: "Active" },
                { value: "false", label: "Inactive" },
              ]}
            />
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={resetFilters}>Reset</Button>
            <Button type="button" onClick={() => {
              updateListQuery({
                organization_code: filterDraft.organizationCode || null,
                firstname: filterDraft.firstName || null,
                lastname: filterDraft.lastName || null,
                email: filterDraft.email || null,
                phone: filterDraft.phone || null,
                active: filterDraft.active || null,
                paginate_page: "1",
              });
              setFilterOpen(false);
            }}>Apply Filters</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={downloadOpen} onOpenChange={setDownloadOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>Download Data</DialogTitle>
            <DialogDescription>Choose your download preferences.</DialogDescription>
          </DialogHeader>
          <div className="space-y-5">
            <div>
              <p className="field-label">Selection</p>
              <div className="mt-2 grid gap-3">
                <label className="flex items-center gap-3 text-sm">
                  <input type="radio" name="downloadScope" checked={downloadScope === "page"} onChange={() => setDownloadScope("page")} />
                  This page only ({visibleCustomers.length} records)
                </label>
                <label className="flex items-center gap-3 text-sm">
                  <input type="radio" name="downloadScope" checked={downloadScope === "filtered"} onChange={() => setDownloadScope("filtered")} />
                  All filtered data ({pagination.totalDocs} records)
                </label>
              </div>
            </div>
            <SelectField
              label="File Type"
              name="downloadFormat"
              value={downloadFormat}
              onChange={(event) => setDownloadFormat(event.target.value as ExportFormat)}
              options={[
                { value: "pdf", label: "PDF" },
                { value: "xlsx", label: "Excel (XLSX)" },
                { value: "csv", label: "CSV" },
              ]}
            />
            {downloadError && <p role="alert" className="text-sm text-destructive">{downloadError}</p>}
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setDownloadOpen(false)}>Cancel</Button>
            <Button type="button" onClick={downloadCustomers} disabled={downloading || !pagination.totalDocs}>
              {downloading ? "Preparing..." : "Download"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </section>
  );
}
