'use client';

import { useState, useEffect, useCallback } from 'react';

interface Props {
  companyId?: string;
  selectedCompany: 'rmp' | 'jtr';
  companies: any[];
}

function fmt(n: number) {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(n);
}

export default function ClientsTab({ companyId, selectedCompany, companies }: Props) {
  const [clients, setClients] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showCreate, setShowCreate] = useState(false);
  const [selectedClient, setSelectedClient] = useState<any>(null);
  const [form, setForm] = useState({
    name: '', organization: '', email: '', phone: '', billing_address: '', notes: '',
    invoice_consolidation: false,
  });

  const loadClients = useCallback(() => {
    setLoading(true);
    const params = companyId ? `?companyId=${companyId}` : '';
    fetch(`/api/billing/clients${params}`)
      .then(r => r.json())
      .then(d => setClients(d.data || []))
      .finally(() => setLoading(false));
  }, [companyId]);

  useEffect(() => { loadClients(); }, [loadClients]);

  const filtered = clients.filter(c =>
    !search ||
    c.name?.toLowerCase().includes(search.toLowerCase()) ||
    c.organization?.toLowerCase().includes(search.toLowerCase()) ||
    c.email?.toLowerCase().includes(search.toLowerCase())
  );

  const handleSave = async () => {
    await fetch('/api/billing/clients', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        client: {
          ...form,
          company_id: companyId,
          ...(selectedClient ? { id: selectedClient.id, mooninvoice_contact_id: selectedClient.mooninvoice_contact_id } : {}),
        },
        moonCompany: selectedCompany,
      }),
    });
    setShowCreate(false);
    setSelectedClient(null);
    setForm({ name: '', organization: '', email: '', phone: '', billing_address: '', notes: '', invoice_consolidation: false });
    loadClients();
  };

  const openEdit = (client: any) => {
    setSelectedClient(client);
    setForm({
      name: client.name || '',
      organization: client.organization || '',
      email: client.email || '',
      phone: client.phone || '',
      billing_address: client.billing_address || '',
      notes: client.notes || '',
      invoice_consolidation: client.invoice_consolidation || false,
    });
    setShowCreate(true);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <input
          type="text"
          placeholder="Search clients..."
          value={search}
          onChange={e => setSearch(e.target.value)}
          className="bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 placeholder-gray-500 w-64 focus:outline-none focus:border-blue-500"
        />
        <div className="ml-auto">
          <button
            onClick={() => { setSelectedClient(null); setForm({ name: '', organization: '', email: '', phone: '', billing_address: '', notes: '', invoice_consolidation: false }); setShowCreate(true); }}
            className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
          >
            + Add Client
          </button>
        </div>
      </div>

      <div className="bg-gray-900 border border-gray-800 rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-gray-800 text-gray-400 text-xs uppercase tracking-wide">
                <th className="text-left px-4 py-3">Client</th>
                <th className="text-left px-4 py-3">Email</th>
                <th className="text-left px-4 py-3">Phone</th>
                <th className="text-left px-4 py-3">Total Billed</th>
                <th className="text-left px-4 py-3">Total Paid</th>
                <th className="text-left px-4 py-3">Outstanding</th>
                <th className="text-left px-4 py-3">Actions</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={7} className="text-center py-12 text-gray-500">Loading...</td></tr>
              ) : filtered.length === 0 ? (
                <tr><td colSpan={7} className="text-center py-12 text-gray-500">No clients found.</td></tr>
              ) : filtered.map(client => (
                <tr key={client.id} className="border-b border-gray-800 hover:bg-gray-800/50 transition-colors">
                  <td className="px-4 py-3">
                    <div className="font-medium text-gray-200">{client.name}</div>
                    {client.organization && <div className="text-xs text-gray-500">{client.organization}</div>}
                  </td>
                  <td className="px-4 py-3 text-gray-400">{client.email || '—'}</td>
                  <td className="px-4 py-3 text-gray-400">{client.phone || '—'}</td>
                  <td className="px-4 py-3 text-gray-200">{fmt(client.total_billed || 0)}</td>
                  <td className="px-4 py-3 text-green-400">{fmt(client.total_paid || 0)}</td>
                  <td className="px-4 py-3 text-yellow-400">{fmt((client.total_billed || 0) - (client.total_paid || 0))}</td>
                  <td className="px-4 py-3">
                    <button onClick={() => openEdit(client)} className="px-2 py-1 bg-gray-700 text-gray-300 rounded text-xs hover:bg-gray-600 transition-colors">
                      Edit
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Create/Edit Modal */}
      {showCreate && (
        <div className="fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4">
          <div className="bg-gray-900 border border-gray-700 rounded-xl w-full max-w-lg">
            <div className="flex items-center justify-between p-5 border-b border-gray-800">
              <h2 className="text-lg font-semibold text-white">{selectedClient ? 'Edit Client' : 'Add Client'}</h2>
              <button onClick={() => setShowCreate(false)} className="text-gray-400 hover:text-white">✕</button>
            </div>
            <div className="p-5 space-y-3">
              {[
                { label: 'Name *', key: 'name', type: 'text' },
                { label: 'Organization', key: 'organization', type: 'text' },
                { label: 'Email', key: 'email', type: 'email' },
                { label: 'Phone', key: 'phone', type: 'text' },
                { label: 'Billing Address', key: 'billing_address', type: 'text' },
              ].map(f => (
                <div key={f.key}>
                  <label className="block text-xs text-gray-400 mb-1">{f.label}</label>
                  <input
                    type={f.type}
                    value={(form as any)[f.key]}
                    onChange={e => setForm(p => ({ ...p, [f.key]: e.target.value }))}
                    className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
                  />
                </div>
              ))}
              <div>
                <label className="block text-xs text-gray-400 mb-1">Internal Notes</label>
                <textarea
                  value={form.notes}
                  onChange={e => setForm(p => ({ ...p, notes: e.target.value }))}
                  rows={2}
                  className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-gray-200 focus:outline-none focus:border-blue-500"
                />
              </div>
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={form.invoice_consolidation}
                  onChange={e => setForm(p => ({ ...p, invoice_consolidation: e.target.checked }))}
                  className="rounded"
                />
                <span className="text-sm text-gray-300">Consolidate multiple campaigns into one monthly invoice</span>
              </label>
            </div>
            <div className="flex justify-end gap-3 p-5 border-t border-gray-800">
              <button onClick={() => setShowCreate(false)} className="px-4 py-2 text-sm text-gray-400 hover:text-white">Cancel</button>
              <button onClick={handleSave} className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium">
                {selectedClient ? 'Save Changes' : 'Add Client'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
