'use client';

import { useEffect, useId, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { MapPin, SlidersHorizontal, Tag, Users2, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { SearchableSelect } from '@/components/ui/SearchableSelect';
import { GENDER_OPTIONS } from '@/lib/gender';
import { REGION_OPTION_GROUPS } from '@/lib/region';
import { categorySearchKeywords } from '@ehandyhire/shared';
import { getCategoryTl } from '@/lib/categoryTl';
import { cn } from '@/lib/utils';

type CategoryOption = { id: string; name: string; slug: string; icon?: string };

export interface WorkersBrowseFilters {
  categorySlug: string;
  gender: string;
  sort: string;
  verified: boolean;
  areaSlug: string;
}

export const defaultWorkersBrowseFilters: WorkersBrowseFilters = {
  categorySlug: '',
  gender: '',
  sort: 'recommended',
  verified: false,
  areaSlug: '',
};

export function countActiveWorkersBrowseFilters(filters: WorkersBrowseFilters) {
  let count = 0;
  if (filters.categorySlug) count += 1;
  if (filters.gender) count += 1;
  if (filters.sort !== 'recommended') count += 1;
  if (filters.verified) count += 1;
  if (filters.areaSlug) count += 1;
  return count;
}

interface WorkersBrowseFilterModalProps {
  open: boolean;
  onClose: () => void;
  filters: WorkersBrowseFilters;
  onChange: (filters: WorkersBrowseFilters) => void;
  categories: CategoryOption[];
  resultCount: number;
}

function FilterChip({
  active,
  onClick,
  children,
}: {
  active: boolean;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        'rounded-full px-3.5 py-2 text-sm font-semibold transition-colors',
        active ? 'bg-[var(--home-ink)] text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
      )}
    >
      {children}
    </button>
  );
}

function FilterSection({
  title,
  children,
}: {
  title: string;
  children: React.ReactNode;
}) {
  return (
    <section className="space-y-2.5">
      <h3 className="text-xs font-semibold uppercase tracking-wide text-muted">{title}</h3>
      {children}
    </section>
  );
}

const SORT_OPTIONS = [
  { value: 'recommended', label: 'Recommended' },
  { value: 'rating', label: 'Highest rated' },
  { value: 'reviews', label: 'Most reviews' },
  { value: 'experience', label: 'Most experience' },
  { value: 'newest', label: 'Newest' },
] as const;

export function WorkersBrowseFilterModal({
  open,
  onClose,
  filters,
  onChange,
  categories,
  resultCount,
}: WorkersBrowseFilterModalProps) {
  const [mounted, setMounted] = useState(false);
  const titleId = useId();

  const categoryOptions = useMemo(
    () =>
      categories.map((cat) => {
        const tl = getCategoryTl(cat.slug)?.nameTl;
        return {
          value: cat.slug,
          label: cat.icon ? `${cat.icon} ${cat.name}` : cat.name,
          keywords: [
            categorySearchKeywords(cat.slug, cat.name),
            tl,
          ]
            .filter(Boolean)
            .join(' '),
        };
      }),
    [categories]
  );

  const locationOptions = useMemo(
    () =>
      REGION_OPTION_GROUPS.flatMap((group) =>
        group.options.map((option) => ({
          value: option.slug,
          label: option.label,
          group: group.label,
          keywords: `${group.label} ${option.slug}`,
        }))
      ),
    []
  );

  const genderOptions = useMemo(
    () =>
      GENDER_OPTIONS.map((option) => ({
        value: option.value,
        label: option.label,
      })),
    []
  );

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!open) return;
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKeyDown);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKeyDown);
      document.body.style.overflow = '';
    };
  }, [open, onClose]);

  const patch = (partial: Partial<WorkersBrowseFilters>) => {
    onChange({ ...filters, ...partial });
  };

  if (!open || !mounted) return null;

  return createPortal(
    <div className="fixed inset-0 z-[9999] flex items-end justify-center sm:items-center sm:p-4">
      <button
        type="button"
        className="absolute inset-0 bg-slate-900/50 backdrop-blur-[1px]"
        aria-label="Close filters"
        onClick={onClose}
      />

      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        className={cn(
          'relative z-[10000] flex w-full max-h-[min(88dvh,100dvh)] flex-col',
          'rounded-t-2xl border border-border bg-surface shadow-2xl sm:max-w-md sm:rounded-2xl'
        )}
      >
        <div className="flex shrink-0 items-center justify-between gap-3 border-b border-border px-5 py-4">
          <div className="flex min-w-0 items-center gap-2.5">
            <div className="flex h-9 w-9 shrink-0 items-center justify-center bg-[var(--home-amber)] text-white">
              <SlidersHorizontal className="h-4 w-4" />
            </div>
            <div className="min-w-0">
              <h2 id={titleId} className="home-display text-base font-bold text-slate-900">
                Filter workers
              </h2>
              <p className="text-xs text-muted">
                {resultCount} worker{resultCount !== 1 ? 's' : ''} match
              </p>
            </div>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="rounded-lg p-2 text-slate-500 hover:bg-slate-100 hover:text-slate-700"
            aria-label="Close"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        <div className="flex-1 space-y-5 overflow-y-auto px-5 py-5">
          <FilterSection title="Category">
            <div className="flex items-center gap-2">
              <Tag className="h-4 w-4 shrink-0 text-slate-400" />
              <SearchableSelect
                value={filters.categorySlug}
                onChange={(categorySlug) => patch({ categorySlug })}
                options={categoryOptions}
                emptyLabel="All categories"
                searchPlaceholder="Search categories…"
              />
            </div>
          </FilterSection>

          <FilterSection title="Location">
            <div className="flex items-center gap-2">
              <MapPin className="h-4 w-4 shrink-0 text-slate-400" />
              <SearchableSelect
                value={filters.areaSlug}
                onChange={(areaSlug) => patch({ areaSlug })}
                options={locationOptions}
                emptyLabel="All locations"
                searchPlaceholder="Search city or region…"
              />
            </div>
          </FilterSection>

          <FilterSection title="Gender">
            <div className="flex items-center gap-2">
              <Users2 className="h-4 w-4 shrink-0 text-slate-400" />
              <SearchableSelect
                value={filters.gender}
                onChange={(gender) => patch({ gender })}
                options={genderOptions}
                emptyLabel="All"
                searchPlaceholder="Search gender…"
              />
            </div>
          </FilterSection>

          <FilterSection title="Sort by">
            <div className="flex flex-wrap gap-2">
              {SORT_OPTIONS.map((option) => (
                <FilterChip
                  key={option.value}
                  active={filters.sort === option.value}
                  onClick={() => patch({ sort: option.value })}
                >
                  {option.label}
                </FilterChip>
              ))}
            </div>
          </FilterSection>

          <FilterSection title="Verification">
            <p className="text-sm text-muted leading-relaxed">
              Only verified workers are shown in the directory.
            </p>
          </FilterSection>
        </div>

        <div className="flex shrink-0 gap-2 border-t border-border px-5 py-4">
          <Button
            type="button"
            variant="outline"
            className="flex-1 rounded-none border-[#d6d0c4]"
            onClick={() => onChange(defaultWorkersBrowseFilters)}
          >
            Reset
          </Button>
          <Button type="button" className="flex-1 worker-cta-amber rounded-none" onClick={onClose}>
            Done
          </Button>
        </div>
      </div>
    </div>,
    document.body
  );
}

export function WorkersBrowseFilterButton({
  activeCount,
  onClick,
}: {
  activeCount: number;
  onClick: () => void;
}) {
  return (
    <Button type="button" variant="outline" size="sm" onClick={onClick} className="gap-1.5 shrink-0 rounded-none border-[#d6d0c4]">
      <SlidersHorizontal className="h-3.5 w-3.5" />
      Filters
      {activeCount > 0 ? (
        <span className="flex h-5 min-w-5 items-center justify-center bg-[var(--home-amber)] px-1.5 text-[10px] font-bold text-white">
          {activeCount}
        </span>
      ) : null}
    </Button>
  );
}
