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_mobile: '',
  street_address: '', city: '', state: 'TX', zip_code: '',
  service_interest: '', last_service_date: '', tag: ''
};

const CustomerList = ({ userId }: { userId: string }) => {
  const [customers, setCustomers] = 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(() => { fetchCustomers(); }, []);

  const fetchCustomers = async () => {
    let query = supabase.from('customer_list').select('*').order('last_name', { ascending: true });
    if (userId) query = query.eq('user_id', userId);
    const { data } = await query;
    if (data) setCustomers(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('customer_list')
        .insert([{ ...formData, user_id: userId }]);
      if (error) throw error;
      const name = `${formData.first_name} ${formData.last_name}`;
      setFormData(emptyForm);
      toast.success(`${name} added to B2C list.`);
      fetchCustomers();
    } catch (error: any) {
      toast.error(error.message);
    } finally {
      setLoading(false);
    }
  };

  const openEdit = (customer: any) => {
    setEditingEntry(customer);
    setEditForm({
      first_name: customer.first_name || '',
      last_name: customer.last_name || '',
      email: customer.email || '',
      phone_mobile: customer.phone_mobile || '',
      street_address: customer.street_address || '',
      city: customer.city || '',
      state: customer.state || 'TX',
      zip_code: customer.zip_code || '',
      service_interest: customer.service_interest || '',
      last_service_date: customer.last_service_date || '',
      tag: customer.tag || '',
    });
  };

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

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

  const filteredCustomers = customers.filter(c => {
    const s = `${c.first_name} ${c.last_name} ${c.email} ${c.phone_mobile} ${c.service_interest} ${c.tag}`.toLowerCase();
    return s.includes(searchTerm.toLowerCase());
  });

  return (
    <div className="max-w-4xl mx-auto space-y-8">
      {showImport && <CSVImport listType="b2c" userId={userId} onComplete={fetchCustomers} onClose={() => setShowImport(false)} />}
      <div className="bg-white p-8 rounded-xl shadow-lg border-t-4 border-green-600">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-bold text-green-900">Residential Customer Entry</h2>
          <button onClick={() => setShowImport(true)} className="bg-green-50 text-green-700 border border-green-200 px-4 py-2 rounded-lg text-xs font-bold uppercase tracking-widest hover:bg-green-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="Mobile Phone *" value={formData.phone_mobile} onChange={e => setFormData({...formData, phone_mobile: e.target.value})} required />
          <input className="border p-3 rounded md:col-span-2" placeholder="Street Address" value={formData.street_address} onChange={e => setFormData({...formData, street_address: e.target.value})} />
          <input className="border p-3 rounded" placeholder="City" value={formData.city} onChange={e => setFormData({...formData, city: e.target.value})} />
          <div className="grid grid-cols-2 gap-2">
            <input className="border p-3 rounded" placeholder="State" value={formData.state} onChange={e => setFormData({...formData, state: e.target.value})} />
            <input className="border p-3 rounded" placeholder="Zip Code" value={formData.zip_code} onChange={e => setFormData({...formData, zip_code: e.target.value})} />
          </div>
          <input className="border p-3 rounded" placeholder="Service Interest" value={formData.service_interest} onChange={e => setFormData({...formData, service_interest: e.target.value})} />
          <input className="border p-3 rounded" type="text" placeholder="Last Service Date (e.g. mm/dd/yyyy)" value={formData.last_service_date} onChange={e => setFormData({...formData, last_service_date: e.target.value})} />
          <input className="border p-3 rounded md:col-span-2" placeholder="Tag (e.g. VIP Lead)" value={formData.tag} onChange={e => setFormData({...formData, tag: e.target.value})} />
          <button type="submit" disabled={loading || validating} className="md:col-span-2 bg-green-600 text-white p-4 rounded-lg font-bold hover:bg-green-700 transition disabled:opacity-60">
            {validating ? 'Validating email…' : loading ? 'Adding Customer…' : 'Add Customer to List'}
          </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">Residential Directory ({filteredCustomers.length})</h3>
          <input
            type="text"
            placeholder="Search by name, email, or interest..."
            className="border p-2 rounded-lg w-1/2 text-sm focus:ring-2 focus:ring-green-500 outline-none"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>

        <table className="w-full text-sm">
          <thead className="bg-green-50 text-green-900">
            <tr>
              <th className="p-4 text-left">Customer Name</th>
              <th className="p-4 text-left">Interest</th>
              <th className="p-4 text-left">Contact Info</th>
              <th className="p-4 text-center w-24">Actions</th>
            </tr>
          </thead>
          <tbody>
            {filteredCustomers.map(c => (
              <tr key={c.id} className="border-t hover:bg-gray-50 transition">
                <td className="p-4 font-bold text-green-900">{c.last_name}, {c.first_name}</td>
                <td className="p-4 text-gray-700">{c.service_interest}</td>
                <td className="p-4">
                  <div className="text-gray-700 font-medium">{c.phone_mobile}</div>
                  <div className="text-xs text-green-600">{c.email}</div>
                </td>
                <td className="p-4 text-center">
                  <div className="flex justify-center gap-2">
                    <button onClick={() => openEdit(c)} title="Edit" className="p-1.5 rounded hover:bg-green-100 text-green-600 transition">
                      <Pencil size={15} />
                    </button>
                    <button onClick={() => handleDelete(c)} title="Delete" className="p-1.5 rounded hover:bg-red-100 text-red-500 transition">
                      <Trash2 size={15} />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
            {filteredCustomers.length === 0 && (
              <tr><td colSpan={4} className="p-8 text-center text-gray-400 italic">No customers 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-green-900">Edit Customer</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 col-span-2" placeholder="Mobile Phone" value={editForm.phone_mobile} onChange={e => setEditForm({...editForm, phone_mobile: 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="Service Interest" value={editForm.service_interest} onChange={e => setEditForm({...editForm, service_interest: e.target.value})} />
              <input className="border p-3 rounded" placeholder="Last Service Date" value={editForm.last_service_date} onChange={e => setEditForm({...editForm, last_service_date: e.target.value})} />
              <input className="border p-3 rounded" 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-green-600 text-white p-3 rounded-lg font-bold hover:bg-green-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 CustomerList;
