"use client";

import React, { useState } from "react";
import { Search } from "lucide-react";
import type { SampleCategory } from "@/services/joomlaService";

interface SampleSubjectFilterProps {
  categories: SampleCategory[];
  currentSubjectAlias: string;
  basePath?: string;
}

export const SampleSubjectFilter: React.FC<SampleSubjectFilterProps> = ({
  categories,
  currentSubjectAlias,
  basePath = "/free-samples",
}) => {
  const [searchQuery, setSearchQuery] = useState("");

  const handleSubjectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const val = e.target.value;
    if (val) {
      window.location.href = `${basePath}/${val}`;
    }
  };

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchQuery.trim()) {
      window.location.href = `/search?q=${encodeURIComponent(searchQuery.trim())}`;
    }
  };

  return (
    <form onSubmit={handleSearchSubmit} className="flex flex-col sm:flex-row gap-3 mb-6">
      <select
        defaultValue={currentSubjectAlias}
        onChange={handleSubjectChange}
        className="sm:w-72 appearance-none bg-white rounded-lg border border-slate-200 px-3 py-2.5 text-sm text-slate-700 shadow-sm focus:outline-none focus:ring-2 focus:ring-[#5C7A36]/40"
        aria-label="Choose the academic paper type"
      >
        <option value="">Choose the Academic Paper Type</option>
        {categories.map((cat) => (
          <option key={cat.alias} value={cat.alias}>
            {cat.title}
          </option>
        ))}
      </select>
      <div className="relative flex-1">
        <input
          type="text"
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          placeholder="Enter a keyword"
          className="w-full rounded-lg border border-slate-200 bg-white pl-3 pr-10 py-2.5 text-sm text-slate-700 shadow-sm focus:outline-none focus:ring-2 focus:ring-[#5C7A36]/40"
        />
        <button
          type="submit"
          aria-label="Search"
          className="absolute right-0 top-0 h-full px-3 text-slate-400 hover:text-[#5C7A36]"
        >
          <Search className="w-4 h-4" />
        </button>
      </div>
    </form>
  );
};
