'use client';

import { useState, useCallback, useRef, useEffect } from 'react';
import type { ContactFilterParams } from '@/app/contacts/page';

interface Props {
  onChange: (filters: ContactFilterParams) => void;
}

const STATUS_OPTIONS = [
  { value: '', label: 'All Statuses' },
  { value: 'new', label: 'New' },
  { value: 'hot', label: 'Hot Lead' },
  { value: 'warm', label: 'Warm' },
  { value: 'cold', label: 'Cold' },
  { value: 'active', label: 'Active' },
  { value: 'closed', label: 'Closed' },
];

export function ContactFilters({ onChange }: Props) {
  const [search, setSearch] = useState('');
  const [status, setStatus] = useState('');
  const [bot, setBot] = useState('');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [bots, setBots] = useState<{ id: string; name: string }[]>([]);

  const debounceRef = useRef<ReturnType<typeof setTimeout>>();

  // Fetch available bots for the dropdown
  useEffect(() => {
    fetch('/api/contacts?limit=0')
      .catch(() => null); // silent fail — bots are optional
    // Try to load routes for bot names
    fetch('/api/routes')
      .then((r) => r.ok ? r.json() : { routes: [] })
      .then((data) => {
        const routes = data.routes || [];
        const botList = routes
          .filter((r: { bot_name?: string; closebot_bot_id?: string }) => r.bot_name)
          .map((r: { closebot_bot_id: string; bot_name: string }) => ({
            id: r.closebot_bot_id,
            name: r.bot_name,
          }));
        // Deduplicate by name
        const seen = new Set<string>();
        setBots(botList.filter((b: { name: string }) => {
          if (seen.has(b.name)) return false;
          seen.add(b.name);
          return true;
        }));
      })
      .catch(() => setBots([]));
  }, []);

  const emitChange = useCallback(
    (overrides: Partial<ContactFilterParams> = {}) => {
      const filters: ContactFilterParams = {
        search: overrides.search ?? search,
        status: overrides.status ?? status,
        bot: overrides.bot ?? bot,
        dateFrom: overrides.dateFrom ?? dateFrom,
        dateTo: overrides.dateTo ?? dateTo,
      };
      // Strip empty values
      Object.keys(filters).forEach((k) => {
        const key = k as keyof ContactFilterParams;
        if (!filters[key]) delete filters[key];
      });
      onChange(filters);
    },
    [search, status, bot, dateFrom, dateTo, onChange]
  );

  const handleSearch = (value: string) => {
    setSearch(value);
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => {
      emitChange({ search: value });
    }, 300);
  };

  const handleExportCSV = async () => {
    try {
      const params = new URLSearchParams();
      if (search) params.set('search', search);
      if (status) params.set('status', status);
      if (bot) params.set('bot', bot);

      const res = await fetch(`/api/contacts/export?${params.toString()}`);
      if (!res.ok) throw new Error('Export failed');

      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `contacts-export-${new Date().toISOString().split('T')[0]}.csv`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch (err) {
      console.error('Export failed:', err);
    }
  };

  const selectStyle: React.CSSProperties = {
    background: 'var(--bg-tertiary)',
    color: 'var(--text-primary)',
    border: '1px solid var(--border)',
  };

  return (
    <div className="card p-4">
      <div className="flex flex-wrap items-center gap-3">
        {/* Search */}
        <div className="relative flex-1 min-w-[220px]">
          <svg
            className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            style={{ color: 'var(--text-muted)' }}
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <input
            type="text"
            placeholder="Search by name, phone, or email..."
            value={search}
            onChange={(e) => handleSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2 rounded-lg text-sm outline-none focus:ring-2 transition-shadow"
            style={{
              ...selectStyle,
              '--tw-ring-color': 'var(--accent-cyan)',
            } as React.CSSProperties}
          />
        </div>

        {/* Status dropdown */}
        <select
          value={status}
          onChange={(e) => {
            setStatus(e.target.value);
            emitChange({ status: e.target.value });
          }}
          className="px-3 py-2 rounded-lg text-sm outline-none focus:ring-2 transition-shadow cursor-pointer"
          style={{
            ...selectStyle,
            '--tw-ring-color': 'var(--accent-cyan)',
          } as React.CSSProperties}
        >
          {STATUS_OPTIONS.map((opt) => (
            <option key={opt.value} value={opt.value}>{opt.label}</option>
          ))}
        </select>

        {/* Bot dropdown */}
        <select
          value={bot}
          onChange={(e) => {
            setBot(e.target.value);
            emitChange({ bot: e.target.value });
          }}
          className="px-3 py-2 rounded-lg text-sm outline-none focus:ring-2 transition-shadow cursor-pointer"
          style={{
            ...selectStyle,
            '--tw-ring-color': 'var(--accent-cyan)',
          } as React.CSSProperties}
        >
          <option value="">All Bots</option>
          {bots.map((b) => (
            <option key={b.id} value={b.id}>{b.name}</option>
          ))}
        </select>

        {/* Date From */}
        <input
          type="date"
          value={dateFrom}
          onChange={(e) => {
            setDateFrom(e.target.value);
            emitChange({ dateFrom: e.target.value });
          }}
          className="px-3 py-2 rounded-lg text-sm outline-none focus:ring-2 transition-shadow"
          style={{
            ...selectStyle,
            '--tw-ring-color': 'var(--accent-cyan)',
          } as React.CSSProperties}
          title="From date"
        />

        {/* Date To */}
        <input
          type="date"
          value={dateTo}
          onChange={(e) => {
            setDateTo(e.target.value);
            emitChange({ dateTo: e.target.value });
          }}
          className="px-3 py-2 rounded-lg text-sm outline-none focus:ring-2 transition-shadow"
          style={{
            ...selectStyle,
            '--tw-ring-color': 'var(--accent-cyan)',
          } as React.CSSProperties}
          title="To date"
        />

        {/* Action Buttons */}
        <div className="flex items-center gap-2 ml-auto">
          <button
            className="flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium transition-colors"
            style={{
              background: 'transparent',
              color: 'var(--accent-cyan)',
              border: '1px solid var(--accent-cyan)',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'rgba(34, 211, 238, 0.1)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'transparent';
            }}
            onClick={() => {
              // Trigger file upload for import
              const input = document.createElement('input');
              input.type = 'file';
              input.accept = '.csv,.json';
              input.onchange = () => {
                // TODO: wire up import endpoint
                console.log('Import file selected:', input.files?.[0]?.name);
              };
              input.click();
            }}
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
            </svg>
            Import Contacts
          </button>

          <button
            onClick={handleExportCSV}
            className="flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium transition-colors"
            style={{
              background: 'transparent',
              color: 'var(--accent-cyan)',
              border: '1px solid var(--accent-cyan)',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'rgba(34, 211, 238, 0.1)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'transparent';
            }}
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
            </svg>
            Export CSV
          </button>
        </div>
      </div>
    </div>
  );
}
