'use client';

import { useEffect, useId, useState } from 'react';
import { createPortal } from 'react-dom';
import { SlidersHorizontal, MapPin, Tag, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  defaultWorkerJobFeedFilters,
  type JobFeedFilter,
  type WorkerJobFeedFilters,
  type WorkerJobFeedSort,
} from '@/components/jobs/JobFeed';
import { REGION_OPTION_GROUPS } from '@/lib/region';
import { cn } from '@/lib/utils';

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

interface WorkerJobFeedFilterModalProps {
  open: boolean;
  onClose: () => void;
  filters: WorkerJobFeedFilters;
  onChange: (filters: WorkerJobFeedFilters) => 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-primary 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>
  );
}

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

  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<WorkerJobFeedFilters>) => {
    onChange({ ...filters, ...partial });
  };

  const feedTabs: { key: JobFeedFilter; label: string }[] = [
    { key: 'all', label: 'All jobs' },
    { key: 'new', label: 'New' },
  ];

  const sortTabs: { key: WorkerJobFeedSort; label: string }[] = [
    { key: 'newest', label: 'Newest' },
    { key: 'budget-high', label: 'Highest budget' },
    { key: 'budget-low', label: 'Lowest budget' },
  ];

  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 items-center gap-2.5 min-w-0">
            <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
              <SlidersHorizontal className="h-4 w-4" />
            </div>
            <div className="min-w-0">
              <h2 id={titleId} className="text-base font-bold text-slate-900">
                Filter jobs
              </h2>
              <p className="text-xs text-muted">
                {resultCount} job{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="Show">
            <div className="flex flex-wrap gap-2">
              {feedTabs.map((tab) => (
                <FilterChip
                  key={tab.key}
                  active={filters.feed === tab.key}
                  onClick={() => patch({ feed: tab.key })}
                >
                  {tab.label}
                </FilterChip>
              ))}
            </div>
          </FilterSection>

          <FilterSection title="Category">
            <div className="flex items-center gap-2">
              <Tag className="h-4 w-4 shrink-0 text-slate-400" />
              <select
                value={filters.categorySlug}
                onChange={(e) => patch({ categorySlug: e.target.value })}
                className="form-select h-11 w-full text-sm"
              >
                <option value="">All categories</option>
                {categories.map((cat) => (
                  <option key={cat.id} value={cat.slug}>
                    {cat.icon ? `${cat.icon} ` : ''}
                    {cat.name}
                  </option>
                ))}
              </select>
            </div>
          </FilterSection>

          <FilterSection title="Region">
            <div className="flex items-center gap-2">
              <MapPin className="h-4 w-4 shrink-0 text-slate-400" />
              <select
                value={filters.regionSlug}
                onChange={(e) => patch({ regionSlug: e.target.value })}
                className="form-select h-11 w-full text-sm"
              >
                <option value="">All regions</option>
                {REGION_OPTION_GROUPS.map((group) => (
                  <optgroup key={group.id} label={group.label}>
                    {group.options.map((option) => (
                      <option key={option.slug} value={option.slug}>
                        {option.label}
                      </option>
                    ))}
                  </optgroup>
                ))}
              </select>
            </div>
          </FilterSection>

          <FilterSection title="Status">
            <div className="flex flex-wrap gap-2">
              {(
                [
                  { key: 'all', label: 'Any status' },
                  { key: 'OPEN', label: 'Open' },
                  { key: 'QUOTED', label: 'Has quotes' },
                ] as const
              ).map((tab) => (
                <FilterChip
                  key={tab.key}
                  active={filters.status === tab.key}
                  onClick={() => patch({ status: tab.key })}
                >
                  {tab.label}
                </FilterChip>
              ))}
            </div>
          </FilterSection>

          <FilterSection title="Budget">
            <div className="flex flex-wrap gap-2">
              {(
                [
                  { key: 'all', label: 'Any' },
                  { key: 'yes', label: 'With budget' },
                  { key: 'no', label: 'Negotiable' },
                ] as const
              ).map((tab) => (
                <FilterChip
                  key={tab.key}
                  active={filters.hasBudget === tab.key}
                  onClick={() => patch({ hasBudget: tab.key })}
                >
                  {tab.label}
                </FilterChip>
              ))}
            </div>
          </FilterSection>

          <FilterSection title="Sort by">
            <div className="flex flex-wrap gap-2">
              {sortTabs.map((tab) => (
                <FilterChip
                  key={tab.key}
                  active={filters.sort === tab.key}
                  onClick={() => patch({ sort: tab.key })}
                >
                  {tab.label}
                </FilterChip>
              ))}
            </div>
          </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"
            onClick={() => onChange(defaultWorkerJobFeedFilters)}
          >
            Reset
          </Button>
          <Button type="button" className="flex-1" onClick={onClose}>
            Done
          </Button>
        </div>
      </div>
    </div>,
    document.body
  );
}

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