'use client';

import { useState, useEffect, useCallback } from 'react';
import { Search, Filter, SlidersHorizontal, MessageSquare } from 'lucide-react';
import { cn, formatPhone, relativeTime, truncate } from '@/lib/utils';
import { hashColor, getInitials } from './message-bubble';

interface ConversationItem {
  id: string;
  phone: string;
  name: string | null;
  status: string;
  last_message: string | null;
  last_message_at: string | null;
  unread_count: number;
  message_count: number;
  bot_name: string | null;
}

interface ConversationListProps {
  selectedId: string | null;
  onSelect: (contactId: string) => void;
}

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

export function ConversationList({ selectedId, onSelect }: ConversationListProps) {
  const [conversations, setConversations] = useState<ConversationItem[]>([]);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [loading, setLoading] = useState(true);
  const [showFilters, setShowFilters] = useState(false);

  const fetchConversations = useCallback(async () => {
    try {
      const params = new URLSearchParams();
      if (search) params.set('search', search);
      if (statusFilter) params.set('status', statusFilter);
      params.set('limit', '100');
      const res = await fetch(`/api/conversations?${params}`);
      if (res.ok) {
        const data = await res.json();
        setConversations(data.conversations || []);
      }
    } catch (err) {
      console.error('Failed to load conversations:', err);
    } finally {
      setLoading(false);
    }
  }, [search, statusFilter]);

  useEffect(() => {
    fetchConversations();
    const interval = setInterval(fetchConversations, 8000);
    return () => clearInterval(interval);
  }, [fetchConversations]);

  // Debounced search
  const [searchInput, setSearchInput] = useState('');
  useEffect(() => {
    const t = setTimeout(() => setSearch(searchInput), 350);
    return () => clearTimeout(t);
  }, [searchInput]);

  return (
    <div className="flex flex-col h-full bg-[#0f1729] border-r border-[#334155]">
      {/* Header */}
      <div className="flex-shrink-0 px-4 pt-5 pb-3">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-bold text-slate-100 flex items-center gap-2">
            <MessageSquare className="w-5 h-5 text-cyan-400" />
            Conversations
          </h2>
          <span className="text-xs text-slate-500 num">{conversations.length}</span>
        </div>

        {/* Search */}
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500" />
          <input
            type="text"
            placeholder="Search contacts..."
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            className="w-full bg-[#1a2332] border border-[#334155] rounded-lg pl-10 pr-20 py-2.5 text-sm text-slate-100 placeholder:text-slate-500 focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-colors"
          />
          <div className="absolute right-2 top-1/2 -translate-y-1/2 flex gap-1">
            <button
              onClick={() => setShowFilters(!showFilters)}
              className={cn(
                'p-1.5 rounded-md transition-colors',
                showFilters ? 'bg-cyan-500/20 text-cyan-400' : 'text-slate-500 hover:text-slate-300 hover:bg-[#334155]'
              )}
            >
              <Filter className="w-3.5 h-3.5" />
            </button>
            <button className="p-1.5 rounded-md text-slate-500 hover:text-slate-300 hover:bg-[#334155] transition-colors">
              <SlidersHorizontal className="w-3.5 h-3.5" />
            </button>
          </div>
        </div>

        {/* Filter dropdown */}
        {showFilters && (
          <div className="mt-2">
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="w-full bg-[#1a2332] border border-[#334155] rounded-lg px-3 py-2 text-sm text-slate-300 focus:outline-none focus:border-cyan-500/50 cursor-pointer"
            >
              {STATUS_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
          </div>
        )}
      </div>

      {/* Conversation list */}
      <div className="flex-1 overflow-y-auto">
        {loading ? (
          <div className="flex items-center justify-center h-32">
            <div className="w-6 h-6 border-2 border-cyan-400/30 border-t-cyan-400 rounded-full animate-spin" />
          </div>
        ) : conversations.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-48 text-slate-500 px-6 text-center">
            <MessageSquare className="w-10 h-10 mb-3 opacity-30" />
            <p className="text-sm font-medium">No conversations yet</p>
            <p className="text-xs mt-1 opacity-70">Conversations will appear when contacts message in</p>
          </div>
        ) : (
          conversations.map((conv) => {
            const isSelected = selectedId === conv.id;
            const displayName = conv.name || formatPhone(conv.phone);
            const color = hashColor(displayName);
            const initials = getInitials(conv.name || conv.phone.slice(-4));

            return (
              <button
                key={conv.id}
                onClick={() => onSelect(conv.id)}
                className={cn(
                  'w-full flex items-start gap-3 px-4 py-3.5 text-left transition-all duration-150 border-l-[3px] border-l-transparent',
                  isSelected
                    ? 'bg-[#1a2332] border-l-cyan-400'
                    : 'hover:bg-[#1a2332]/60'
                )}
              >
                {/* Avatar */}
                <div
                  className="w-10 h-10 rounded-full flex items-center justify-center text-white text-sm font-bold flex-shrink-0"
                  style={{ backgroundColor: color }}
                >
                  {initials}
                </div>

                {/* Content */}
                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between gap-2">
                    <span className="font-semibold text-sm text-cyan-300 truncate">
                      {conv.name || 'Unknown'}
                    </span>
                    {conv.last_message_at && (
                      <span className="text-[11px] text-slate-500 flex-shrink-0 num">
                        {relativeTime(conv.last_message_at)}
                      </span>
                    )}
                  </div>
                  <p className="text-[11px] text-slate-500 mt-0.5">{formatPhone(conv.phone)}</p>
                  <div className="flex items-center justify-between mt-1">
                    <p className="text-xs text-slate-400 truncate pr-2">
                      {conv.last_message ? truncate(conv.last_message, 40) : 'No messages yet'}
                    </p>
                    {conv.unread_count > 0 && (
                      <span className="flex-shrink-0 w-5 h-5 bg-cyan-500 text-white text-[10px] font-bold rounded-full flex items-center justify-center">
                        {conv.unread_count > 9 ? '9+' : conv.unread_count}
                      </span>
                    )}
                  </div>
                </div>
              </button>
            );
          })
        )}
      </div>
    </div>
  );
}
