"use client";

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

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

export const QuestionSubjectFilter: React.FC<QuestionSubjectFilterProps> = ({
  categories,
  currentSubjectAlias,
  basePath = "/answers",
}) => {
  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 (
    <div className="flex flex-col sm:flex-row items-center gap-3">
      <div className="w-full sm:w-60 shrink-0">
        <select
          defaultValue={currentSubjectAlias}
          onChange={handleSubjectChange}
          className="w-full appearance-none rounded-lg border border-slate-300 bg-white px-3.5 py-2.5 text-sm font-medium text-slate-700 shadow-sm focus:border-[#5C7A36] focus:outline-none focus:ring-1 focus:ring-[#5C7A36]"
          aria-label="Choose subject"
        >
          <option value="" disabled>
            Choose the Subjects
          </option>
          {categories.map((cat) => (
            <option key={cat.alias} value={cat.alias}>
              {cat.title}
            </option>
          ))}
        </select>
      </div>

      <form onSubmit={handleSearchSubmit} className="flex-1 w-full flex items-center gap-2">
        <input
          type="text"
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          placeholder="What do you want to know?"
          className="w-full rounded-lg border border-slate-300 bg-white px-3.5 py-2.5 text-sm text-slate-700 shadow-sm focus:border-[#5C7A36] focus:outline-none focus:ring-1 focus:ring-[#5C7A36]"
        />
        <button
          type="submit"
          aria-label="Search"
          className="rounded-lg bg-[#f58e0e] hover:bg-[#e47d00] p-2.5 text-white transition-colors shrink-0"
        >
          <Search className="w-5 h-5" />
        </button>
      </form>
    </div>
  );
};
