"use client";

import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { EmployeeDeptFilterId } from "@/features/employees/employee-filter-config";
import { EMPLOYEE_DEPT_FILTERS } from "@/features/employees/employee-filter-config";
import { Check } from "lucide-react";
import { useCallback, useEffect, useState } from "react";

export type EmployeeWorkTypeFilter = "Office" | "Remote" | null;

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  appliedDepartments: Set<EmployeeDeptFilterId>;
  appliedWorkType: EmployeeWorkTypeFilter;
  onApply: (departments: Set<EmployeeDeptFilterId>, workType: EmployeeWorkTypeFilter) => void;
};

function toggleSet<T>(set: Set<T>, key: T): Set<T> {
  const next = new Set(set);
  if (next.has(key)) next.delete(key);
  else next.add(key);
  return next;
}

export default function EmployeesFilterPanel({
  open,
  onOpenChange,
  appliedDepartments,
  appliedWorkType,
  onApply,
}: Props) {
  const [draftDept, setDraftDept] = useState<Set<EmployeeDeptFilterId>>(() => new Set());
  const [draftType, setDraftType] = useState<EmployeeWorkTypeFilter>(null);

  useEffect(() => {
    if (!open) return;
    setDraftDept(new Set(appliedDepartments));
    setDraftType(appliedWorkType);
  }, [open, appliedDepartments, appliedWorkType]);

  const onKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (e.key === "Escape") onOpenChange(false);
    },
    [onOpenChange],
  );

  useEffect(() => {
    if (!open) return;
    document.addEventListener("keydown", onKeyDown);
    return () => document.removeEventListener("keydown", onKeyDown);
  }, [open, onKeyDown]);

  if (!open) return null;

  const pairs: (typeof EMPLOYEE_DEPT_FILTERS[number] | undefined)[][] = [];
  for (let i = 0; i < EMPLOYEE_DEPT_FILTERS.length; i += 2) {
    pairs.push([EMPLOYEE_DEPT_FILTERS[i], EMPLOYEE_DEPT_FILTERS[i + 1]]);
  }

  return (
    <div className="fixed inset-0 z-50 flex justify-end">
      <button
        type="button"
        className="absolute inset-0 bg-black/40"
        aria-label="Close filters"
        onClick={() => onOpenChange(false)}
      />
      <div
        className="relative m-4 mt-[120px] h-max max-h-[calc(100vh-140px)] w-[323px] shrink-0 overflow-y-auto rounded-xl bg-white p-6 shadow-[0px_4px_32px_0px_rgba(61,70,112,0.08)]"
        role="dialog"
        aria-modal="true"
        aria-labelledby="employees-filter-title"
      >
        <div className="flex flex-col gap-6">
          <h2
            id="employees-filter-title"
            className="text-base font-bold capitalize leading-snug text-[#1C1D22]"
          >
            Filter
          </h2>

          <div className="flex flex-col gap-4">
            <div className="flex flex-col gap-3">
              <p className="text-xs font-normal leading-snug text-[#53545C]">Department</p>
              <div className="flex flex-col gap-3">
                {pairs.map((pair, rowIdx) => (
                  <div key={rowIdx} className="flex w-full items-start justify-between gap-2">
                    {pair.map((opt) =>
                      opt ? (
                        <label
                          key={opt.id}
                          className="flex min-w-0 flex-1 cursor-pointer items-center gap-3"
                        >
                          <span
                            className={cn(
                              "flex size-6 shrink-0 items-center justify-center rounded-lg border",
                              draftDept.has(opt.id)
                                ? "border-[#6D7DCD] bg-[#074473]"
                                : "border-[#CFD3D4] bg-white",
                            )}
                          >
                            {draftDept.has(opt.id) ? (
                              <Check className="size-3 text-white" strokeWidth={3} aria-hidden />
                            ) : null}
                          </span>
                          <input
                            type="checkbox"
                            className="sr-only"
                            checked={draftDept.has(opt.id)}
                            onChange={() => setDraftDept((s) => toggleSet(s, opt.id))}
                          />
                          <span
                            className={cn(
                              "min-w-0 flex-1 text-sm font-medium leading-snug",
                              draftDept.has(opt.id) ? "text-[#2B2F32]" : "text-[#83898C]",
                            )}
                          >
                            {opt.label}
                          </span>
                        </label>
                      ) : (
                        <span key={`empty-${rowIdx}`} className="flex-1" />
                      ),
                    )}
                  </div>
                ))}
              </div>
            </div>

            <div className="h-px w-full bg-[#F1F3F9]" aria-hidden />

            <div className="flex flex-col gap-3">
              <p className="text-xs font-normal leading-snug text-[#53545C]">Select Type</p>
              <div className="flex w-full items-start justify-between gap-2">
                <button
                  type="button"
                  className="flex min-w-0 flex-1 items-center gap-3 text-left"
                  onClick={() => setDraftType((t) => (t === "Office" ? null : "Office"))}
                >
                  <span
                    className={cn(
                      "flex size-6 shrink-0 items-center justify-center rounded-full border",
                      draftType === "Office" ? "border-[#6D7DCD]" : "border-[#CFD3D4]",
                    )}
                  >
                    <span
                      className={cn(
                        "size-3.5 rounded-full",
                        draftType === "Office" ? "bg-[#074473]" : "bg-transparent",
                      )}
                    />
                  </span>
                  <span
                    className={cn(
                      "min-w-0 flex-1 text-sm font-medium leading-snug",
                      draftType === "Office" ? "text-[#2B2F32]" : "text-[#83898C]",
                    )}
                  >
                    Office
                  </span>
                </button>
                <button
                  type="button"
                  className="flex min-w-0 flex-1 items-center gap-3 text-left"
                  onClick={() => setDraftType((t) => (t === "Remote" ? null : "Remote"))}
                >
                  <span
                    className={cn(
                      "flex size-6 shrink-0 items-center justify-center rounded-full border",
                      draftType === "Remote" ? "border-[#6D7DCD]" : "border-[#CFD3D4]",
                    )}
                  >
                    <span
                      className={cn(
                        "size-3.5 rounded-full",
                        draftType === "Remote" ? "bg-[#074473]" : "bg-transparent",
                      )}
                    />
                  </span>
                  <span
                    className={cn(
                      "min-w-0 flex-1 text-sm font-medium leading-snug",
                      draftType === "Remote" ? "text-[#2B2F32]" : "text-[#83898C]",
                    )}
                  >
                    Work From Home
                  </span>
                </button>
              </div>
            </div>
          </div>

          <Button
            type="button"
            className="h-9 w-full rounded-md bg-[#074473] text-sm font-medium text-white hover:bg-[#074473]/90"
            onClick={() => {
              onApply(new Set(draftDept), draftType);
              onOpenChange(false);
            }}
          >
            Filter
          </Button>
        </div>
      </div>
    </div>
  );
}
