"use client";

import { GlobeIcon, SearchIcon } from "@/assets/icons";
import { Checkbox } from "@/components/FormElements/checkbox";
import DatePicker from "@/components/FormElements/DatePicker/DatePicker";
import InputGroup from "@/components/FormElements/InputGroup";
import { Select } from "@/components/FormElements/select";
import { Button } from "@/components/ui-elements/button";
import CollapsibleFilterSection from "@/components/ui/CollapsibleFilterSection";
import InlineListFiltersPanel from "@/components/ui/InlineListFiltersPanel";
import { Countries } from "@/constants/countries";
import { isDateRangeActive } from "@/utils/shared";
import { useMemo } from "react";
import {
  Control,
  FieldValues,
  UseFormHandleSubmit,
  UseFormRegister,
  UseFormSetValue,
  UseFormWatch,
} from "react-hook-form";

interface TenderListFiltersProps {
  filterRegister: UseFormRegister<FieldValues>;
  control: Control<FieldValues>;
  isMutating: number;
  handleFilterSubmit: UseFormHandleSubmit<FieldValues>;
  search: (data: any) => void;
  watch: UseFormWatch<FieldValues>;
  setValue: UseFormSetValue<any>;
  onClearAll: () => void;
}

const RANGE_KEYS = [
  "created_at_range",
  "tender_deadline_range",
  "publication_date_range",
  "submission_deadline_range",
] as const;

function countActiveFilters(values: Record<string, unknown>): number {
  let n = 0;
  const textKeys = [
    "q",
    "title",
    "description",
    "country_codes",
    "notice_type",
    "notice_types",
    "form_types",
    "main_classification",
    "classifications",
  ];
  for (const key of textKeys) {
    const v = values[key];
    if (typeof v === "string" && v.trim()) n++;
  }
  const country = values.country;
  if (typeof country === "string" && country.trim()) n++;
  for (const key of RANGE_KEYS) {
    if (isDateRangeActive(values[key])) n++;
  }
  if (values.documents_scraped === true) n++;
  return n;
}

const TenderListFilters = ({
  filterRegister,
  control,
  isMutating,
  handleFilterSubmit,
  search,
  watch,
  setValue,
  onClearAll,
}: TenderListFiltersProps) => {
  const watched = watch();
  const activeCount = useMemo(
    () => countActiveFilters(watched as Record<string, unknown>),
    [watched],
  );

  return (
    <InlineListFiltersPanel
      title="Refine tenders"
      activeFilterCount={activeCount}
      expandAriaLabel="Expand tender filters"
      collapseAriaLabel="Collapse tender filters"
      panelToggleDataCy="tenders-filter-panel-toggle"
    >
      <form
        className="space-y-4 px-4 pb-6 pt-1 sm:px-6"
        onSubmit={handleFilterSubmit(search)}
      >
        {/* Hero search */}
        <div className="flex flex-col gap-3 lg:flex-row lg:items-end">
          <div className="min-h-[52px] flex-1">
            <InputGroup
              {...filterRegister("q")}
              name="q"
              label="Keyword search"
              type="text"
              placeholder="Title, buyer, CPV — cast a wide net…"
              icon={
                <SearchIcon className="text-primary dark:text-primary/90" />
              }
              iconPosition="left"
              className="[&_input]:rounded-2xl [&_input]:border-stroke/70 [&_input]:bg-white/90 [&_input]:py-3.5 [&_input]:text-sm dark:[&_input]:border-dark-3 dark:[&_input]:bg-dark-2/80"
            />
          </div>
          <div className="flex shrink-0 flex-col gap-2 sm:flex-row sm:items-center">
            <Button
              type="submit"
              size="small"
              className="min-h-[52px] min-w-[140px] rounded-2xl bg-gradient-to-r from-primary via-primary to-violet-600 px-8 text-sm font-semibold transition hover:opacity-[0.97]"
              label={
                isMutating ? (
                  <span className="inline-flex h-5 w-5 animate-spin rounded-full border-2 border-white/30 border-t-white" />
                ) : (
                  <span>Apply filters</span>
                )
              }
            />
            <button
              type="button"
              onClick={onClearAll}
              className="min-h-[52px] rounded-2xl border border-stroke/70 bg-white/80 px-6 text-sm font-semibold text-dark transition hover:border-primary/40 hover:text-primary dark:border-dark-3 dark:bg-dark-3/60 dark:text-white dark:hover:bg-white/[0.06]"
            >
              Reset all
            </button>
          </div>
        </div>

        <CollapsibleFilterSection
          title="Scope & geography"
          subtitle="Country pick or comma-separated codes for multi-region searches."
        >
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
            <Select<FieldValues>
              {...filterRegister("country")}
              name="country"
              label="Country"
              items={Countries}
              placeholder="Any country"
              searchable
              searchPlaceholder="Search country or code…"
              clearable
              prefixIcon={<GlobeIcon />}
              value={watch("country")}
              onClear={() => setValue("country", "")}
            />
            <InputGroup
              {...filterRegister("country_codes")}
              name="country_codes"
              label="Country codes"
              type="text"
              placeholder="e.g. SWE, DEU"
            />
          </div>
        </CollapsibleFilterSection>

        <CollapsibleFilterSection
          title="Notice & classification"
          subtitle="TED notice dimensions and CPV-style filters."
        >
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
            <InputGroup
              {...filterRegister("title")}
              name="title"
              label="Title contains"
              type="text"
            />
            <InputGroup
              {...filterRegister("description")}
              name="description"
              label="Description contains"
              type="text"
            />
            <InputGroup
              {...filterRegister("notice_type")}
              name="notice_type"
              label="Notice type"
              type="text"
            />
            <InputGroup
              {...filterRegister("notice_types")}
              name="notice_types"
              label="Notice types (comma-separated)"
              type="text"
            />
            <InputGroup
              {...filterRegister("form_types")}
              name="form_types"
              label="Form types (comma-separated)"
              type="text"
            />
            <InputGroup
              {...filterRegister("main_classification")}
              name="main_classification"
              label="Main classification"
              type="text"
            />
            <InputGroup
              {...filterRegister("classifications")}
              name="classifications"
              label="Classifications (comma-separated)"
              type="text"
            />
          </div>
        </CollapsibleFilterSection>

        <CollapsibleFilterSection
          title="Document state"
          subtitle="Restrict to tenders whose documents have been scraped."
        >
          <div className="max-w-fit rounded-xl border border-stroke/40 bg-white/60 p-4 dark:border-white/[0.06] dark:bg-dark-3/40">
            <Checkbox
              label="Documents scraped"
              minimal
              withBg
              withIcon="check"
              {...filterRegister("documents_scraped")}
            />
          </div>
        </CollapsibleFilterSection>

        <CollapsibleFilterSection
          title="Date ranges"
          subtitle="Unix-backed ranges — pick start/end; cleared ranges are omitted from the query."
          badge="Time travel"
        >
          <div className="grid gap-5 lg:grid-cols-2">
            <div className="rounded-xl border border-stroke/40 bg-white/60 p-3 dark:border-white/[0.06] dark:bg-dark-3/40">
              <DatePicker
                control={control}
                name="created_at_range"
                label="Created at"
                range
                timePicker
                clearable
                portal
              />
            </div>
            <div className="rounded-xl border border-stroke/40 bg-white/60 p-3 dark:border-white/[0.06] dark:bg-dark-3/40">
              <DatePicker
                control={control}
                name="tender_deadline_range"
                label="Tender deadline"
                range
                timePicker
                clearable
                portal
              />
            </div>
            <div className="rounded-xl border border-stroke/40 bg-white/60 p-3 dark:border-white/[0.06] dark:bg-dark-3/40">
              <DatePicker
                control={control}
                name="publication_date_range"
                label="Publication date"
                range
                timePicker
                clearable
                portal
              />
            </div>
            <div className="rounded-xl border border-stroke/40 bg-white/60 p-3 dark:border-white/[0.06] dark:bg-dark-3/40">
              <DatePicker
                control={control}
                name="submission_deadline_range"
                label="Submission deadline"
                range
                timePicker
                clearable
                portal
              />
            </div>
          </div>
        </CollapsibleFilterSection>
      </form>
    </InlineListFiltersPanel>
  );
};

export default TenderListFilters;
