"use client";

import { useEffect, useState } from "react";
import type { DiskFilters, TireFilters } from "@/types/product";
import { seasonLabels } from "@/types/product";

export interface FilterState {
  brand?: string;
  width?: number;
  height?: number;
  diameter?: number;
  season?: string;
  pcd?: string;
  diskType?: string;
}

interface Props {
  category: "tire" | "disk";
  options: TireFilters | DiskFilters | null;
  value: FilterState;
  onApply: (value: FilterState) => void;
  onClose: () => void;
}

function Chip({
  active,
  children,
  onClick,
}: {
  active: boolean;
  children: React.ReactNode;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`rounded-full border px-3 py-1.5 text-xs font-medium transition-colors ${
        active
          ? "border-[var(--tg-accent)] bg-[var(--tg-accent)] text-white"
          : "border-white/15 bg-white/5 text-[var(--tg-hint)]"
      }`}
    >
      {children}
    </button>
  );
}

export default function FilterSheet({ category, options, value, onApply, onClose }: Props) {
  const [draft, setDraft] = useState<FilterState>(value);

  useEffect(() => {
    setDraft(value);
  }, [value]);

  const tireOptions = category === "tire" ? (options as TireFilters | null) : null;
  const diskOptions = category === "disk" ? (options as DiskFilters | null) : null;

  return (
    <div className="fixed inset-0 z-50 flex items-end bg-black/60" onClick={onClose}>
      <div
        className="safe-bottom max-h-[85vh] w-full overflow-y-auto rounded-t-3xl bg-[var(--tg-surface)] p-5"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="mx-auto mb-4 h-1 w-10 rounded-full bg-white/20" />
        <h2 className="mb-4 text-lg font-bold">Фильтры</h2>

        {tireOptions && (
          <div className="flex flex-col gap-4">
            <FilterGroup label="Бренд">
              {tireOptions.brands.map((brand) => (
                <Chip
                  key={brand}
                  active={draft.brand === brand}
                  onClick={() =>
                    setDraft((d) => ({ ...d, brand: d.brand === brand ? undefined : brand }))
                  }
                >
                  {brand}
                </Chip>
              ))}
            </FilterGroup>
            <FilterGroup label="Ширина">
              {tireOptions.widths.map((width) => (
                <Chip
                  key={width}
                  active={draft.width === width}
                  onClick={() =>
                    setDraft((d) => ({ ...d, width: d.width === width ? undefined : width }))
                  }
                >
                  {width}
                </Chip>
              ))}
            </FilterGroup>
            <FilterGroup label="Профиль">
              {tireOptions.heights.map((height) => (
                <Chip
                  key={height}
                  active={draft.height === height}
                  onClick={() =>
                    setDraft((d) => ({ ...d, height: d.height === height ? undefined : height }))
                  }
                >
                  {height}
                </Chip>
              ))}
            </FilterGroup>
            <FilterGroup label="Диаметр">
              {tireOptions.diameters.map((diameter) => (
                <Chip
                  key={diameter}
                  active={draft.diameter === diameter}
                  onClick={() =>
                    setDraft((d) => ({
                      ...d,
                      diameter: d.diameter === diameter ? undefined : diameter,
                    }))
                  }
                >
                  R{diameter}
                </Chip>
              ))}
            </FilterGroup>
            <FilterGroup label="Сезон">
              {tireOptions.seasons.map((season) => (
                <Chip
                  key={season}
                  active={draft.season === season}
                  onClick={() =>
                    setDraft((d) => ({ ...d, season: d.season === season ? undefined : season }))
                  }
                >
                  {seasonLabels[season] ?? season}
                </Chip>
              ))}
            </FilterGroup>
          </div>
        )}

        {diskOptions && (
          <div className="flex flex-col gap-4">
            <FilterGroup label="Бренд">
              {diskOptions.brands.map((brand) => (
                <Chip
                  key={brand}
                  active={draft.brand === brand}
                  onClick={() =>
                    setDraft((d) => ({ ...d, brand: d.brand === brand ? undefined : brand }))
                  }
                >
                  {brand}
                </Chip>
              ))}
            </FilterGroup>
            <FilterGroup label="Диаметр">
              {diskOptions.diameters.map((diameter) => (
                <Chip
                  key={diameter}
                  active={draft.diameter === diameter}
                  onClick={() =>
                    setDraft((d) => ({
                      ...d,
                      diameter: d.diameter === diameter ? undefined : diameter,
                    }))
                  }
                >
                  R{diameter}
                </Chip>
              ))}
            </FilterGroup>
            <FilterGroup label="Сверловка (PCD)">
              {diskOptions.pcds.map((pcd) => (
                <Chip
                  key={pcd}
                  active={draft.pcd === pcd}
                  onClick={() => setDraft((d) => ({ ...d, pcd: d.pcd === pcd ? undefined : pcd }))}
                >
                  {pcd}
                </Chip>
              ))}
            </FilterGroup>
            <FilterGroup label="Тип диска">
              {diskOptions.diskTypes.map((type) => (
                <Chip
                  key={type}
                  active={draft.diskType === type}
                  onClick={() =>
                    setDraft((d) => ({ ...d, diskType: d.diskType === type ? undefined : type }))
                  }
                >
                  {type}
                </Chip>
              ))}
            </FilterGroup>
          </div>
        )}

        <div className="mt-6 flex gap-3">
          <button
            type="button"
            onClick={() => {
              setDraft({});
              onApply({});
            }}
            className="flex-1 rounded-xl border border-white/15 py-3 text-sm font-semibold text-[var(--tg-hint)]"
          >
            Сбросить
          </button>
          <button
            type="button"
            onClick={() => onApply(draft)}
            className="flex-1 rounded-xl bg-[var(--tg-accent)] py-3 text-sm font-semibold text-white"
          >
            Показать
          </button>
        </div>
      </div>
    </div>
  );
}

function FilterGroup({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div>
      <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-[var(--tg-hint)]">
        {label}
      </p>
      <div className="flex flex-wrap gap-2">{children}</div>
    </div>
  );
}
