import { Constituency, District } from '@/type/localtion.type';
import { useMemo } from 'react';

const ComparisonFilter = ({
  selectedDistrict,
  selectedConstituency,
  handleDistrictChange,
  handleConstituencyChange,
  districts,
  constituencies,
}: {
  selectedDistrict: string;
  selectedConstituency: string;
  handleDistrictChange: (e: React.ChangeEvent<HTMLSelectElement>) => void;
  handleConstituencyChange: (e: React.ChangeEvent<HTMLSelectElement>) => void;
  districts: District[];
  constituencies: Constituency[];
}) => {
  const selectedDistrictConstituencies = useMemo(() => {
    try {
      return constituencies.filter((c) => c.district_id === selectedDistrict);
    } catch (error) {
      return [];
    }
  }, [selectedDistrict, constituencies]);

  return (
    <section className="mb-3 md:mb-10 animate-fade-in">
      <div className="bg-white rounded-xl md:rounded-3xl p-2 sm:p-3 md:p-8 shadow-sm border border-blue-100">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-2 md:gap-6">
          <div>
            <label className="block text-xs sm:text-sm font-bold text-gray-700 mb-1.5 sm:mb-2">
              জেলা
            </label>
            <select
              value={selectedDistrict}
              onChange={handleDistrictChange}
              className="w-full bg-gray-50 border border-gray-200 rounded-lg sm:rounded-xl px-3 py-2 sm:px-4 sm:py-3 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none"
            >
              <option value="">জেলা নির্বাচন করুন</option>
              {districts.map((district) => (
                <option key={district.id} value={district.id}>
                  {district.name_bn}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-xs sm:text-sm font-bold text-gray-700 mb-1.5 sm:mb-2">
              নির্বাচনী এলাকা
            </label>
            <select
              value={selectedConstituency}
              onChange={handleConstituencyChange}
              disabled={!selectedDistrict}
              className="w-full bg-gray-50 border border-gray-200 rounded-lg sm:rounded-xl px-3 py-2 sm:px-4 sm:py-3 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <option value="">
                {selectedDistrict ? 'নির্বাচনী এলাকা নির্বাচন করুন' : 'আগে জেলা নির্বাচন করুন'}
              </option>
              {selectedDistrict &&
                selectedDistrictConstituencies.map((constituency) => (
                  <option key={constituency.id} value={constituency.id}>
                    {constituency.name}
                  </option>
                ))}
            </select>
          </div>
        </div>
      </div>
    </section>
  );
};

export default ComparisonFilter;
