'use client';

import { useState } from 'react';
import { ContactFilters } from '@/components/contacts/contact-filters';
import { ContactsTable } from '@/components/contacts/contacts-table';
import { ContactDetailPanel } from '@/components/contacts/contact-detail-panel';

export interface ContactFilterParams {
  search?: string;
  status?: string;
  bot?: string;
  dateFrom?: string;
  dateTo?: string;
}

export default function ContactsPage() {
  const [selectedContactId, setSelectedContactId] = useState<string | null>(null);
  const [filters, setFilters] = useState<ContactFilterParams>({});
  const [refreshKey, setRefreshKey] = useState(0);

  const handleFilterChange = (newFilters: ContactFilterParams) => {
    setFilters(newFilters);
    setSelectedContactId(null);
  };

  const handleContactUpdated = () => {
    setRefreshKey((k) => k + 1);
  };

  return (
    <div className="min-h-screen p-6" style={{ background: 'var(--bg-primary)' }}>
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-white tracking-tight">Contacts / Leads</h1>
        <p className="text-sm mt-1" style={{ color: 'var(--text-secondary)' }}>
          Manage your contacts, track lead status, and view conversation history.
        </p>
      </div>

      {/* Filters */}
      <ContactFilters onChange={handleFilterChange} />

      {/* Table + Detail Panel */}
      <div className="flex gap-4 mt-4">
        <div className={`transition-all duration-300 ${selectedContactId ? 'flex-1 min-w-0' : 'w-full'}`}>
          <ContactsTable
            filters={filters}
            refreshKey={refreshKey}
            selectedContactId={selectedContactId}
            onSelect={(id) => setSelectedContactId(id === selectedContactId ? null : id)}
          />
        </div>

        {selectedContactId && (
          <ContactDetailPanel
            contactId={selectedContactId}
            onClose={() => setSelectedContactId(null)}
            onUpdated={handleContactUpdated}
          />
        )}
      </div>
    </div>
  );
}
