'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import { agentsService, AgentType } from '@/services/agents.service';
import { profileSectionsService } from '@/services/profile-sections.service';
import type { HeroContent } from '@/types/cms';

const defaultHeroContent: HeroContent = {
  headline: 'Discover verified, top-rated real estate professionals to guide your buying, selling, or investing journey.',
  description: '',
  ctaButtonText: 'See All',
  helperText: '',
};

export function HeroSection({ content }: { content?: HeroContent }) {
  const data = content ?? defaultHeroContent;
  const router = useRouter();
  const [agentTypes, setAgentTypes] = useState<AgentType[]>([]);
  const [specializationOptions, setSpecializationOptions] = useState<{ id: string; name: string }[]>([]);
  const [specializationSlug, setSpecializationSlug] = useState<string>('');
  const [locationOptions, setLocationOptions] = useState<{ label: string; value: string }[]>([]);
  const [searchParams, setSearchParams] = useState({
    specialization: '',
    type: '',
    name: '',
    location: '',
  });
  const [openDropdown, setOpenDropdown] = useState<string | null>(null);
  const [validationError, setValidationError] = useState<string | null>(null);

  // Fetch agent types and specialization options on mount
  useEffect(() => {
    const fetchAgentTypes = async () => {
      try {
        const types = await agentsService.getAgentTypes();
        setAgentTypes(types);
      } catch (error) {
        console.error('Failed to fetch agent types:', error);
      }
    };
    const fetchSpecializations = async () => {
      try {
        const fields = await profileSectionsService.getFilterableFields();
        const specField = fields.find(f => f.slug.includes('specialization'));
        if (specField) {
          setSpecializationSlug(specField.slug);
          setSpecializationOptions(specField.options.map(o => ({ id: o.value, name: o.label })));
        }
        // Collect city + state options for location autocomplete.
        // Cities in the system may carry a state prefix (e.g. "ne_adams") — strip it for display.
        const formatCity = (label: string) => label.replace(/^[A-Z]{2}\s*[-–—]\s*/, '').trim();
        const locs: { label: string; value: string }[] = [];
        const seen = new Set<string>();
        for (const f of fields) {
          if (f.slug === 'state') {
            for (const opt of f.options) {
              const key = `state:${opt.label.toLowerCase()}`;
              if (seen.has(key)) continue;
              seen.add(key);
              locs.push({ label: opt.label, value: opt.label });
            }
          } else if (f.slug === 'city') {
            for (const opt of f.options) {
              const clean = formatCity(opt.label);
              const key = `city:${clean.toLowerCase()}`;
              if (seen.has(key)) continue;
              seen.add(key);
              locs.push({ label: clean, value: clean });
            }
          }
        }
        setLocationOptions(locs);
      } catch (error) {
        console.error('Failed to fetch specializations:', error);
      }
    };
    fetchAgentTypes();
    fetchSpecializations();
  }, []);

  const filteredLocationOptions = searchParams.location.trim()
    ? locationOptions.filter(o => o.label.toLowerCase().includes(searchParams.location.trim().toLowerCase())).slice(0, 8)
    : [];

  const handleSearch = () => {
    // Validate that at least one field has a value
    const hasType = searchParams.type.trim() !== '';
    const hasName = searchParams.name.trim() !== '';
    const hasLocation = searchParams.location.trim() !== '';
    const hasSpecialization = searchParams.specialization.trim() !== '';

    if (!hasType && !hasName && !hasLocation && !hasSpecialization) {
      setValidationError('Please enter at least one search criteria (Type, Name/Keyword, Location, or Specialization)');
      return;
    }

    // Clear any previous validation error
    setValidationError(null);

    const params = new URLSearchParams();
    if (searchParams.type) params.set('type', searchParams.type);
    if (searchParams.name) params.set('name', searchParams.name);
    if (searchParams.location) params.set('location', searchParams.location);
    if (searchParams.specialization && specializationSlug) {
      params.set('filters', JSON.stringify({ [specializationSlug]: [searchParams.specialization] }));
    }
    router.push(`/user/profiles?${params.toString()}`);
  };

  const handleSeeAllAgents = () => {
    router.push('/user/profiles');
  };

  const toggleDropdown = (dropdown: string) => {
    setOpenDropdown(openDropdown === dropdown ? null : dropdown);
  };

  const selectSpecialization = (value: string) => {
    setSearchParams({ ...searchParams, specialization: value });
    setOpenDropdown(null);
    setValidationError(null);
  };

  const selectType = (value: string) => {
    setSearchParams({ ...searchParams, type: value });
    setOpenDropdown(null);
    setValidationError(null); // Clear error when user selects a type
  };

  const handleInputChange = (field: 'name' | 'location', value: string) => {
    setSearchParams({ ...searchParams, [field]: value });
    setValidationError(null); // Clear error when user starts typing
  };

  const handleClearError = () => {
    setValidationError(null);
  };

  return (
    <section className="relative min-h-[540px] md:h-[540px] overflow-hidden">
      {/* Background Image */}
      <div className="absolute inset-0">
        <Image
          src="/assets/images/user_home_top.png"
          alt=""
          fill
          className="object-cover object-bottom"
          priority
        />
      </div>

      <div className="relative max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 pt-20 pb-10 md:pt-28 min-h-[540px] md:h-[540px] flex flex-col">
        {/* Headline */}
        <div className="text-center mb-8">
          <h1 className="font-fractul font-bold text-[24px] md:text-[28px] lg:text-[30px] leading-[50px] text-[#00293d] max-w-4xl mx-auto">
            {data.headline}
          </h1>
          {data.description && (
            <p className="font-fractul font-bold text-[20px] md:text-[24px] leading-[40px] text-[#00293d] mt-2">
              {data.description}
            </p>
          )}
        </div>

        {/* Search Form */}
        <div className="max-w-5xl mx-auto relative">
          <div className="bg-[#e58625] rounded-[15px] shadow-lg p-3">
            <div className="flex flex-col md:flex-row gap-2">
              {/* Type Select */}
              <div className="relative flex-shrink-0 md:w-[160px]">
                <button
                  onClick={() => toggleDropdown('type')}
                  className="w-full h-[42px] px-4 rounded-[7px] border border-[#00293d]/10 bg-white text-left flex items-center justify-between focus:outline-none"
                >
                  <span className="font-serif text-sm text-[#00293d]">
                    {searchParams.type ? agentTypes.find(t => t.id === searchParams.type)?.name : 'Types'}
                  </span>
                  <Image
                    src="/assets/icons/chevron-down-icon.svg"
                    alt=""
                    width={10}
                    height={10}
                    className={`transition-transform ${openDropdown === 'type' ? 'rotate-180' : ''}`}
                  />
                </button>
                {openDropdown === 'type' && (
                  <div className="absolute top-full left-0 right-0 mt-0 bg-white rounded-[7px] border border-[#00293d]/10 shadow-lg z-20 overflow-hidden max-h-[200px] overflow-y-auto">
                    {agentTypes.map((type, index, arr) => (
                      <button
                        key={type.id}
                        onClick={() => selectType(type.id)}
                        className={`w-full px-4 py-2.5 text-left font-serif text-sm text-[#00293d] hover:bg-[#00293d]/5 ${index < arr.length - 1 ? 'border-b border-[#00293d]/10' : ''}`}
                      >
                        {type.name}
                      </button>
                    ))}
                  </div>
                )}
              </div>

              {/* Name Input */}
              <div className="flex-1 md:min-w-[180px]">
                <input
                  type="text"
                  placeholder="Name or Keyword"
                  value={searchParams.name}
                  onChange={(e) => handleInputChange('name', e.target.value)}
                  className="w-full h-[42px] px-4 rounded-[7px] border border-[#00293d]/10 bg-white font-serif text-sm text-[#00293d] placeholder:text-[#00293d] focus:outline-none"
                />
              </div>

              {/* Location Input with autocomplete */}
              <div className="relative flex-1 md:min-w-[140px]">
                <input
                  type="text"
                  placeholder="Location"
                  value={searchParams.location}
                  onChange={(e) => {
                    handleInputChange('location', e.target.value);
                    setOpenDropdown('location');
                  }}
                  onFocus={() => setOpenDropdown('location')}
                  onBlur={() => setTimeout(() => setOpenDropdown((cur) => (cur === 'location' ? null : cur)), 150)}
                  autoComplete="off"
                  className="w-full h-[42px] px-4 rounded-[7px] border border-[#00293d]/10 bg-white font-serif text-sm text-[#00293d] placeholder:text-[#00293d] focus:outline-none"
                />
                {openDropdown === 'location' && filteredLocationOptions.length > 0 && (
                  <div className="absolute top-full left-0 right-0 mt-0 bg-white rounded-[7px] border border-[#00293d]/10 shadow-lg z-20 overflow-hidden max-h-[240px] overflow-y-auto">
                    {filteredLocationOptions.map((option, index, arr) => (
                      <button
                        key={option.value}
                        onMouseDown={(e) => {
                          e.preventDefault();
                          setSearchParams((prev) => ({ ...prev, location: option.value }));
                          setOpenDropdown(null);
                          setValidationError(null);
                        }}
                        className={`w-full px-4 py-2.5 text-left font-serif text-sm text-[#00293d] hover:bg-[#00293d]/5 ${index < arr.length - 1 ? 'border-b border-[#00293d]/10' : ''}`}
                      >
                        {option.label}
                      </button>
                    ))}
                  </div>
                )}
              </div>

              {/* Specialization Select */}
              <div className="relative flex-shrink-0 md:w-[160px]">
                <button
                  onClick={() => toggleDropdown('specialization')}
                  className="w-full h-[42px] px-4 rounded-[7px] border border-[#00293d]/10 bg-white text-left flex items-center justify-between focus:outline-none"
                >
                  <span className="font-serif text-sm text-[#00293d] truncate">
                    {searchParams.specialization ? specializationOptions.find(o => o.id === searchParams.specialization)?.name : 'Specialization'}
                  </span>
                  <Image
                    src="/assets/icons/chevron-down-icon.svg"
                    alt=""
                    width={10}
                    height={10}
                    className={`transition-transform ${openDropdown === 'specialization' ? 'rotate-180' : ''}`}
                  />
                </button>
                {openDropdown === 'specialization' && (
                  <div className="absolute top-full left-0 right-0 mt-0 bg-white rounded-[7px] border border-[#00293d]/10 shadow-lg z-20 overflow-hidden max-h-[200px] overflow-y-auto">
                    {specializationOptions.map((option, index, arr) => (
                      <button
                        key={option.id}
                        onClick={() => selectSpecialization(option.id)}
                        className={`w-full px-4 py-2.5 text-left font-serif text-sm text-[#00293d] hover:bg-[#00293d]/5 ${index < arr.length - 1 ? 'border-b border-[#00293d]/10' : ''}`}
                      >
                        {option.name}
                      </button>
                    ))}
                  </div>
                )}
              </div>

              {/* Search Button */}
              <div className="flex-shrink-0">
                <button
                  onClick={handleSearch}
                  className="w-full md:w-[48px] h-[42px] rounded-[7px] bg-[#00293d] hover:bg-[#00293d]/90 text-white transition-colors flex items-center justify-center"
                >
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M5 12H19M19 12L12 5M19 12L12 19" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </button>
              </div>
            </div>
          </div>

          {/* Validation Error Message (overlay — does not push layout) */}
          {validationError && (
            <div className="pointer-events-none fixed inset-x-0 top-20 z-50 flex justify-center px-4 md:absolute md:top-auto md:bottom-[-56px] md:inset-x-0">
              <div className="pointer-events-auto text-white font-serif text-xs md:text-sm bg-red-500/95 rounded-[7px] py-2 px-3 inline-flex items-center gap-2 max-w-[92%] shadow-lg">
                <span className="text-left">{validationError}</span>
                <button
                  onClick={handleClearError}
                  className="flex-shrink-0 hover:bg-white/20 rounded-full p-0.5 transition-colors"
                  title="Dismiss"
                >
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </button>
              </div>
            </div>
          )}

        </div>

        {/* Bottom Section */}
        <div className="mt-auto pt-6">
          {/* See All Agents Button */}
          <div className="flex justify-center">
            <button
              onClick={handleSeeAllAgents}
              className="px-8 py-3 rounded-[15px] bg-[#e58625] hover:bg-[#d47720] text-[#00293d] font-fractul font-bold text-base transition-colors shadow-md hover:shadow-lg"
            >
              {data.ctaButtonText}
            </button>
          </div>

          {/* Helper Text */}
          {data.helperText && (
            <p className="text-center font-serif font-normal text-[14px] leading-[19px] text-[#00293D] mt-3 max-w-[419px] mx-auto">
              {data.helperText}
            </p>
          )}
        </div>
      </div>
    </section>
  );
}
