'use client';

/**
 * Dealer Search Component
 *
 * Provides search and filter controls for the dealer list.
 * Supports text search and dropdown filters for tier and status.
 */

import React, { useState, useCallback, useRef } from 'react';
import styles from './DealerSearch.module.css';

interface DealerSearchProps {
  onSearch: (params: SearchParams) => void;
  isLoading?: boolean;
  /**
   * Optional external search value. When the parent populates the search
   * programmatically (e.g. At-Risk "Show in table"), passing it here keeps
   * the input box in sync so the value is visible and the Clear button shows.
   */
  searchValue?: string;
}

export interface SearchParams {
  search: string;
  tier: string;
  status: string;
}

const TIERS = [
  { value: '', label: 'All Tiers' },
  { value: 'starter', label: 'Starter' },
  { value: 'growth', label: 'Growth' },
  { value: 'enhanced', label: 'Enhanced' },
  { value: 'professional', label: 'Professional' },
];

const STATUSES = [
  { value: '', label: 'All Statuses' },
  { value: 'active', label: 'Active' },
  { value: 'registration_pending', label: 'Registration Pending' },
  { value: 'registration_complete', label: 'Registration Complete' },
  { value: 'suspended', label: 'Suspended' },
  { value: 'cancelled_pending', label: 'Cancellation Pending' },
  { value: 'cancelled', label: 'Cancellation Complete' },
  { value: 'payment_failed', label: 'Payment Failed' },
];

export function DealerSearch({ onSearch, isLoading, searchValue }: DealerSearchProps) {
  const [search, setSearch] = useState(searchValue ?? '');
  const [tier, setTier] = useState('');
  const [status, setStatus] = useState('');
  const searchInputRef = useRef<HTMLInputElement>(null);

  // Mirror an externally-set search value (e.g. At-Risk "Show in table") into
  // the input. Uses React's "adjust state during render" pattern keyed on the
  // previous prop value rather than an effect — only fires when the parent
  // changes searchValue, and user typing still flows through
  // handleSearchChange, so there's no feedback loop.
  const [prevSearchValue, setPrevSearchValue] = useState(searchValue);
  if (
    searchValue !== undefined &&
    searchValue !== prevSearchValue &&
    // Skip the echo when the parent is just reflecting our own onChange back —
    // only sync when the value genuinely diverges from the input.
    searchValue !== search
  ) {
    setPrevSearchValue(searchValue);
    setSearch(searchValue);
  }

  // Debounce search input
  const handleSearchChange = useCallback(
    (value: string) => {
      setSearch(value);
      // Debounce will be handled by the parent if needed
      onSearch({ search: value, tier, status });
    },
    [onSearch, tier, status]
  );

  const handleTierChange = useCallback(
    (value: string) => {
      setTier(value);
      onSearch({ search, tier: value, status });
    },
    [onSearch, search, status]
  );

  const handleStatusChange = useCallback(
    (value: string) => {
      setStatus(value);
      onSearch({ search, tier, status: value });
    },
    [onSearch, search, tier]
  );

  const handleClear = useCallback(() => {
    setSearch('');
    setTier('');
    setStatus('');
    onSearch({ search: '', tier: '', status: '' });
  }, [onSearch]);

  const hasFilters = search || tier || status;

  return (
    <div className={styles.container}>
      <div className={styles.searchWrapper}>
        <svg
          className={styles.searchIcon}
          viewBox="0 0 20 20"
          fill="currentColor"
          aria-hidden="true"
        >
          <path
            fillRule="evenodd"
            d="M9 3.5a5.5 5.5 0 100 11 5.5 5.5 0 000-11zM2 9a7 7 0 1112.452 4.391l3.328 3.329a.75.75 0 11-1.06 1.06l-3.329-3.328A7 7 0 012 9z"
            clipRule="evenodd"
          />
        </svg>
        <input
          ref={searchInputRef}
          type="text"
          className={styles.searchInput}
          placeholder="Search by name, business, phone, email, subdomain, domain, or dealer #"
          value={search}
          onChange={(e) => handleSearchChange(e.target.value)}
        />
      </div>

      <div className={styles.filters}>
        <select
          className={styles.select}
          value={tier}
          onChange={(e) => handleTierChange(e.target.value)}
          disabled={isLoading}
        >
          {TIERS.map((t) => (
            <option key={t.value} value={t.value}>
              {t.label}
            </option>
          ))}
        </select>

        <select
          className={styles.select}
          value={status}
          onChange={(e) => handleStatusChange(e.target.value)}
          disabled={isLoading}
        >
          {STATUSES.map((s) => (
            <option key={s.value} value={s.value}>
              {s.label}
            </option>
          ))}
        </select>

        {hasFilters && (
          <button
            className={styles.clearButton}
            onClick={handleClear}
            disabled={isLoading}
            type="button"
          >
            Clear
          </button>
        )}
      </div>
    </div>
  );
}
