import { useState, useEffect } from 'react';
import { supabase } from './supabaseClient';
import toast from 'react-hot-toast';
import { Pencil, Trash2, X } from 'lucide-react';
import CSVImport from './CSVImport';

const emptyForm = {
  first_name: '', last_name: '', email: '', phone_office: '',
  company_name: '', job_title: '', industry: '', website: '',
  street_address: '', city: '', state: 'TX', zip_code: '', tag: ''
};

const BusinessPartners = ({ userId }: { userId: string }) => {
  const [partners, setPartners] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [formData, setFormData] = useState(emptyForm);
  const [loading, setLoading] = useState(false);
  const [validating, setValidating] = useState(false);
  const [showImport, setShowImport] = useState(false);
  const [editingEntry, setEditingEntry] = useState<any | null>(null);
  const [editForm, setEditForm] = useState(emptyForm);
  const [saving, setSaving] = useState(false);

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

  const fetchPartners = async () => {
    let query = supabase.from('business_partners').select('*').order('company_name', { ascending: true });
    if (userId) query = query.eq('user_id', userId);
    const { data } = await query;
    if (data) setPartners(data);
  };

  const handleSubmit = async (e: any) => {
    e.preventDefault();
    setLoading(true);
    try {
      setValidating(true);
      try {
        const res = await fetch(`/api/validate-email?email=${encodeURIComponent(formData.email)}`);
        const data = await res.json();
        if (!data.valid) {
          toast.error(`Email rejected: ${data.result} — ${data.reason}`);
          return;
        }
      } catch { /* fail open */ } finally { setValidating(false); }

      const { error } = await supabase
        .from('business_partners')
        .insert([{ ...formData, user_id: userId }]);
      if (error) throw error;
      const name = formData.company_name || `${formData.first_name} ${formData.last_name}`;
      setFormData(emptyForm);
      toast.success(`${name} added to B2B list.`);
      fetchPartners();
    } catch (error: any) {
      toast.error(error.message);
    } finally {
      setLoading(false);
    }
  };

  const openEdit = (partner: any) => {
    setEditingEntry(partner);
    setEditForm({
      first_name: partner.first_name || '',
      last_name: partner.last_name || '',
      email: partner.email || '',
      phone_office: partner.phone_office || '',
      company_name: partner.company_name || '',
      job_title: partner.job_title || '',
      industry: partner.industry || '',
      website: partner.website || '',
      street_address: partner.street_address || '',
      city: partner.city || '',
      state: partner.state || 'TX',
      zip_code: partner.zip_code || '',
      tag: partner.tag || '',
    });
  };

  const handleUpdate = async (e: any) => {
    e.preventDefault();
    setSaving(true);
    try {
      const { error } = await supabase
        .from('business_partners')
        .update(editForm)
        .eq('id', editingEntry.id);
      if (error) throw error;
      const name = editForm.company_name || `${editForm.first_name} ${editForm.last_name}`;
      toast.success(`${name} updated.`);
      setEditingEntry(null);
      fetchPartners();
    } catch (error: any) {
      toast.error(error.message);
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (partner: any) => {
    const name = partner.company_name || `${partner.first_name} ${partner.last_name}`;
    if (!window.confirm(`Delete ${name} from B2B list? This cannot be undone.`)) return;
    try {
      const { error } = await supabase
        .from('business_partners')
        .delete()
        .eq('id', partner.id);
      if (error) throw error;
      toast.success(`${name} removed.`);
      fetchPartners();
    } catch (error: any) {
      toast.error(error.message);
    }
  };

  const filteredPartners = partners.filter(p =>
    `${p.first_name} ${p.last_name} ${p.company_name} ${p.industry}`.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="max-w-4xl mx-auto space-y-8">
      {showImport && <CSVImport listType="b2b" userId={userId} onComplete={fetchPartners} onClose={() => setShowImport(false)} />}
      <div className="bg-white p-8 rounded-xl shadow-lg border-t-4 border-indigo-600">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-bold text-indigo-900">B2B Business Partner Information</h2>
          <button onClick={() => setShowImport(true)} className="bg-indigo-50 text-indigo-700 border border-indigo-200 px-4 py-2 rounded-lg text-xs font-bold uppercase tracking-widest hover:bg-indigo-100 transition">
            ⬆ Import CSV
          </button>
        </div>
        <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <input className="border p-3 rounded" placeholder="First Name *" value={formData.first_name} onChange={e => setFormData({...formData, first_name: e.target.value})} required />
          <input className="border p-3 rounded" placeholder="Last Name *" value={formData.last_name} onChange={e => setFormData({...formData, last_name: e.target.value})} required />
          <input className="border p-3 rounded" placeholder="Email *" type="email" value={formData.email} onChange={e => setFormData({...formData, email: e.target.value})} required />
          <input className="border p-3 rounded" placeholder="Office Phone" value={formData.phone_office} onChange={e => setFormData({...formData, phone_office: e.target.value})} />
          <input className="border p-3 rounded md:col-span-2" placeholder="Company Name" value={formData.company_name} onChange={e => setFormData({...formData, company_name: e.target.value})} />
          <input className="border p-3 rounded" placeholder="Job Title" value={formData.job_title} onChange={e => setFormData({...formData, job_title: e.target.value})} />
          <input className="border p-3 rounded" placeholder="Industry" value={formData.industry} onChange={e => setFormData({...formData, industry: e.target.value})} />
          <input className="border p-3 rounded md:col-span-2" placeholder="Website (e.g. www.company.com)" value={formData.website} onChange={e => setFormData({...formData, website: e.target.value})} />
          <button type="submit" disabled={loading || validating} className="md:col-span-2 bg-indigo-600 text-white p-4 rounded-lg font-bold hover:bg-indigo-700 transition disabled:opacity-60">
            {validating ? 'Validating email…' : loading ? 'Adding Partner…' : 'Register Business Partner'}
          </button>
        </form>
      </div>

      <div className="bg-white rounded-xl shadow-md overflow-hidden border border-gray-100 p-4">
        <div className="flex justify-between items-center mb-4">
          <h3 className="font-bold text-gray-700">Partner Directory ({filteredPartners.length})</h3>
          <input
            type="text"
            placeholder="Search partners, companies, or industries..."
            className="border p-2 rounded-lg w-1/2 text-sm focus:ring-2 focus:ring-indigo-500 outline-none"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>

        <table className="w-full text-sm">
          <thead className="bg-indigo-50 text-indigo-900">
            <tr>
              <th className="p-4 text-left">Partner / Company</th>
              <th className="p-4 text-left">Industry</th>
              <th className="p-4 text-left">Website</th>
              <th className="p-4 text-center w-24">Actions</th>
            </tr>
          </thead>
          <tbody>
            {filteredPartners.map(p => (
              <tr key={p.id} className="border-t hover:bg-gray-50 transition">
                <td className="p-4">
                  <div className="font-bold text-indigo-900">{p.company_name || 'N/A'}</div>
                  <div className="text-xs text-gray-500">{p.first_name} {p.last_name} • {p.job_title}</div>
                </td>
                <td className="p-4 text-gray-700">{p.industry}</td>
                <td className="p-4">
                  <a href={p.website} target="_blank" rel="noreferrer" className="text-blue-600 hover:underline text-xs">{p.website}</a>
                </td>
                <td className="p-4 text-center">
                  <div className="flex justify-center gap-2">
                    <button onClick={() => openEdit(p)} title="Edit" className="p-1.5 rounded hover:bg-indigo-100 text-indigo-600 transition">
                      <Pencil size={15} />
                    </button>
                    <button onClick={() => handleDelete(p)} title="Delete" className="p-1.5 rounded hover:bg-red-100 text-red-500 transition">
                      <Trash2 size={15} />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
            {filteredPartners.length === 0 && (
              <tr><td colSpan={4} className="p-8 text-center text-gray-400 italic">No partners found matching "{searchTerm}"</td></tr>
            )}
          </tbody>
        </table>
      </div>

      {editingEntry && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="flex justify-between items-center p-6 border-b">
              <h3 className="text-lg font-bold text-indigo-900">Edit Business Partner</h3>
              <button onClick={() => setEditingEntry(null)} className="p-1 rounded hover:bg-gray-100 text-gray-500">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={handleUpdate} className="p-6 grid grid-cols-2 gap-4">
              <input className="border p-3 rounded" placeholder="First Name *" value={editForm.first_name} onChange={e => setEditForm({...editForm, first_name: e.target.value})} required />
              <input className="border p-3 rounded" placeholder="Last Name *" value={editForm.last_name} onChange={e => setEditForm({...editForm, last_name: e.target.value})} required />
              <input className="border p-3 rounded col-span-2" placeholder="Email *" type="email" value={editForm.email} onChange={e => setEditForm({...editForm, email: e.target.value})} required />
              <input className="border p-3 rounded" placeholder="Office Phone" value={editForm.phone_office} onChange={e => setEditForm({...editForm, phone_office: e.target.value})} />
              <input className="border p-3 rounded" placeholder="Company Name" value={editForm.company_name} onChange={e => setEditForm({...editForm, company_name: e.target.value})} />
              <input className="border p-3 rounded" placeholder="Job Title" value={editForm.job_title} onChange={e => setEditForm({...editForm, job_title: e.target.value})} />
              <input className="border p-3 rounded" placeholder="Industry" value={editForm.industry} onChange={e => setEditForm({...editForm, industry: e.target.value})} />
              <input className="border p-3 rounded col-span-2" placeholder="Website" value={editForm.website} onChange={e => setEditForm({...editForm, website: e.target.value})} />
              <input className="border p-3 rounded col-span-2" placeholder="Street Address" value={editForm.street_address} onChange={e => setEditForm({...editForm, street_address: e.target.value})} />
              <input className="border p-3 rounded" placeholder="City" value={editForm.city} onChange={e => setEditForm({...editForm, city: e.target.value})} />
              <div className="grid grid-cols-2 gap-2">
                <input className="border p-3 rounded" placeholder="State" value={editForm.state} onChange={e => setEditForm({...editForm, state: e.target.value})} />
                <input className="border p-3 rounded" placeholder="Zip Code" value={editForm.zip_code} onChange={e => setEditForm({...editForm, zip_code: e.target.value})} />
              </div>
              <input className="border p-3 rounded col-span-2" placeholder="Tag" value={editForm.tag} onChange={e => setEditForm({...editForm, tag: e.target.value})} />
              <div className="col-span-2 flex gap-3 pt-2">
                <button type="submit" className="flex-1 bg-indigo-600 text-white p-3 rounded-lg font-bold hover:bg-indigo-700 transition">
                  {saving ? 'Saving...' : 'Save Changes'}
                </button>
                <button type="button" onClick={() => setEditingEntry(null)} className="flex-1 bg-gray-100 text-gray-700 p-3 rounded-lg font-bold hover:bg-gray-200 transition">
                  Cancel
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default BusinessPartners;
