"use client";

import * as React from "react";
import { ArrowUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { ScrollArea } from "@/components/ui/scroll-area";
import { DEALS_FILTER_TRIGGER_ACTIVE_CLASS } from "@/components/deals/deals-filter-styles";

export type DealsSortField = {
  id: string;
  label: string;
  ascLabel: string;
  descLabel: string;
};

export const DEALS_DEFAULT_SORT_COL = "createdDate";
export const DEALS_DEFAULT_SORT_DIR = -1 as const;

export const LEAD_DEAL_SORT_FIELDS: DealsSortField[] = [
  {
    id: "customerName",
    label: "Customer",
    ascLabel: "A – Z",
    descLabel: "Z – A",
  },
  {
    id: "companyName",
    label: "Company",
    ascLabel: "A – Z",
    descLabel: "Z – A",
  },
  {
    id: "createdDate",
    label: "Created",
    ascLabel: "Oldest first",
    descLabel: "Newest first",
  },
  {
    id: "updatedAt",
    label: "Updated",
    ascLabel: "Oldest first",
    descLabel: "Newest first",
  },
];

export function formatDealsSortTooltip(
  sortCol: string,
  sortDir: 1 | -1,
  fields: DealsSortField[] = LEAD_DEAL_SORT_FIELDS,
): string {
  const field = fields.find((f) => f.id === sortCol) ?? fields[0];
  const dirLabel = sortDir === 1 ? field.ascLabel : field.descLabel;
  return `Sort by ${field.label}: ${dirLabel}`;
}

export function isNonDefaultDealsSort(
  sortCol: string,
  sortDir: 1 | -1,
): boolean {
  return sortCol !== DEALS_DEFAULT_SORT_COL || sortDir !== DEALS_DEFAULT_SORT_DIR;
}

type DealsSortPopoverProps = {
  sortCol: string;
  sortDir: 1 | -1;
  onSortChange: (sortCol: string, sortDir: 1 | -1) => void;
  onClearSort?: () => void;
  fields?: DealsSortField[];
  triggerClassName?: string;
  ariaLabel?: string;
};

export function DealsSortPopover({
  sortCol,
  sortDir,
  onSortChange,
  onClearSort,
  fields = LEAD_DEAL_SORT_FIELDS,
  triggerClassName,
  ariaLabel = "Sort leads",
}: DealsSortPopoverProps) {
  const [open, setOpen] = React.useState(false);
  const [activeFieldId, setActiveFieldId] = React.useState(
    () => fields.find((f) => f.id === sortCol)?.id ?? fields[0]?.id ?? "",
  );

  React.useEffect(() => {
    if (!fields.some((field) => field.id === activeFieldId)) {
      setActiveFieldId(fields[0]?.id ?? "");
    }
  }, [fields, activeFieldId]);

  React.useEffect(() => {
    if (fields.some((field) => field.id === sortCol)) {
      setActiveFieldId(sortCol);
    }
  }, [sortCol, fields]);

  const activeField =
    fields.find((field) => field.id === activeFieldId) ?? fields[0];
  const isCustomSort = isNonDefaultDealsSort(sortCol, sortDir);
  const sortLabel = formatDealsSortTooltip(sortCol, sortDir, fields);

  if (fields.length === 0) return null;

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          type="button"
          variant="outline"
          size="icon-xs"
          className={cn(
            "relative",
            triggerClassName,
            isCustomSort && DEALS_FILTER_TRIGGER_ACTIVE_CLASS,
          )}
          aria-label={sortLabel || ariaLabel}
        >
          <ArrowUpDown className="size-4" aria-hidden />
        </Button>
      </PopoverTrigger>
      <PopoverContent
        align="end"
        className="w-[min(100vw-2rem,22rem)] rounded-2xl border-border/40 p-0 shadow-premium"
      >
        <div className="flex max-h-[min(70vh,420px)] min-h-[240px] flex-col sm:flex-row">
          <div className="shrink-0 border-b border-border/40 p-2 sm:w-36 sm:border-b-0 sm:border-r">
            <p className="px-2 pb-1 font-['Lexend_Deca'] text-[10px] font-bold uppercase tracking-widest text-gray-400">
              Sort by
            </p>
            <ScrollArea className="max-h-32 sm:max-h-none">
              <ul className="flex gap-0.5 overflow-x-auto sm:flex-col sm:overflow-x-visible">
                {fields.map((field) => {
                  const isActive = field.id === activeFieldId;
                  const isSelected = field.id === sortCol;
                  return (
                    <li key={field.id}>
                      <button
                        type="button"
                        onClick={() => setActiveFieldId(field.id)}
                        className={cn(
                          "w-full whitespace-nowrap rounded-lg px-2.5 py-1.5 text-left font-['Lexend_Deca'] text-[12px] font-semibold transition-colors sm:whitespace-normal",
                          isActive
                            ? "bg-accent/10 text-accent"
                            : "text-gray-600 hover:bg-gray-50",
                        )}
                      >
                        <span className="flex items-center gap-1.5">
                          {field.label}
                          {isSelected ? (
                            <span
                              className="size-1.5 shrink-0 rounded-full bg-accent"
                              aria-hidden
                            />
                          ) : null}
                        </span>
                      </button>
                    </li>
                  );
                })}
              </ul>
            </ScrollArea>
          </div>

          <div className="flex min-h-0 min-w-0 flex-1 flex-col p-3">
            <p className="mb-2 font-['Lexend_Deca'] text-[11px] font-bold text-gray-700">
              {activeField?.label}
            </p>
            <ScrollArea className="min-h-0 flex-1">
              <ul className="space-y-1 pr-2">
                {(
                  [
                    { dir: 1 as const, label: activeField?.ascLabel ?? "A – Z" },
                    {
                      dir: -1 as const,
                      label: activeField?.descLabel ?? "Z – A",
                    },
                  ] as const
                ).map(({ dir, label }) => {
                  const checked =
                    activeField?.id === sortCol && sortDir === dir;
                  const optionId = `${activeField?.id}-${dir}`;
                  return (
                    <li key={optionId}>
                      <label
                        htmlFor={optionId}
                        className="flex cursor-pointer items-center gap-2.5 rounded-lg px-2 py-1.5 text-[12px] font-medium hover:bg-gray-50"
                      >
                        <Checkbox
                          id={optionId}
                          checked={checked}
                          onCheckedChange={() => {
                            if (!activeField) return;
                            onSortChange(activeField.id, dir);
                            setOpen(false);
                          }}
                        />
                        <span className="truncate">{label}</span>
                      </label>
                    </li>
                  );
                })}
              </ul>
            </ScrollArea>
            {onClearSort ? (
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="mt-2 h-8 w-full text-[12px] font-bold rounded-lg"
                onClick={() => {
                  onClearSort();
                  setOpen(false);
                }}
                disabled={!isCustomSort}
              >
                Clear sort
              </Button>
            ) : null}
          </div>
        </div>
      </PopoverContent>
    </Popover>
  );
}
