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: '',
  company: '', category: '', tag: ''
};

const MemberAdmin = ({ userId }: { userId: string }) => {
  const [members, setMembers] = 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(() => { fetchMembers(); }, []);

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

  const openEdit = (member: any) => {
    setEditingEntry(member);
    setEditForm({
      first_name: member.first_name || '',
      last_name: member.last_name || '',
      email: member.email || '',
      phone: member.phone || '',
      company: member.company || '',
      category: member.category || '',
      tag: member.tag || '',
    });
  };

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

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

  const filteredMembers = members.filter(m => {
    const s = `${m.first_name} ${m.last_name} ${m.email} ${m.phone} ${m.company} ${m.category}`.toLowerCase();
    return s.includes(searchTerm.toLowerCase());
  });

  return (
    <div className="max-w-4xl mx-auto space-y-8">
      {showImport && <CSVImport listType="bnp" userId={userId} onComplete={fetchMembers} onClose={() => setShowImport(false)} />}
      <div className="bg-white p-8 rounded-xl shadow-lg border-t-4 border-blue-600">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-bold text-blue-900">BNP Member Information</h2>
          <button onClick={() => setShowImport(true)} className="bg-blue-50 text-blue-700 border border-blue-200 px-4 py-2 rounded-lg text-xs font-bold uppercase tracking-widest hover:bg-blue-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="Business Phone" value={formData.phone} onChange={e => setFormData({...formData, phone: e.target.value})} />
          <input className="border p-3 rounded" placeholder="Company Name" value={formData.company} onChange={e => setFormData({...formData, company: e.target.value})} />
          <input className="border p-3 rounded" placeholder="Business Category (e.g. Realtor)" value={formData.category} onChange={e => setFormData({...formData, category: e.target.value})} />
          <button type="submit" disabled={loading || validating} className="md:col-span-2 bg-blue-600 text-white p-4 rounded-lg font-bold hover:bg-blue-700 transition disabled:opacity-60">
            {validating ? 'Validating email…' : loading ? 'Adding Member…' : 'Register BNP Member'}
          </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">BNP Member Directory ({filteredMembers.length})</h3>
          <input
            type="text"
            placeholder="Search by name, company, or category..."
            className="border p-2 rounded-lg w-1/2 text-sm focus:ring-2 focus:ring-blue-500 outline-none"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>

        <table className="w-full text-sm">
          <thead className="bg-blue-50 text-blue-900">
            <tr>
              <th className="p-4 text-left">Member Name</th>
              <th className="p-4 text-left">Company / Category</th>
              <th className="p-4 text-left">Contact Info</th>
              <th className="p-4 text-center w-24">Actions</th>
            </tr>
          </thead>
          <tbody>
            {filteredMembers.map(m => (
              <tr key={m.id} className="border-t hover:bg-gray-50 transition">
                <td className="p-4 font-bold text-blue-900">{m.last_name}, {m.first_name}</td>
                <td className="p-4">
                  <div className="font-medium text-gray-900">{m.company}</div>
                  <div className="text-xs text-gray-500">{m.category}</div>
                </td>
                <td className="p-4">
                  <div className="text-gray-700">{m.phone}</div>
                  <div className="text-xs text-blue-600">{m.email}</div>
                </td>
                <td className="p-4 text-center">
                  <div className="flex justify-center gap-2">
                    <button onClick={() => openEdit(m)} title="Edit" className="p-1.5 rounded hover:bg-blue-100 text-blue-600 transition">
                      <Pencil size={15} />
                    </button>
                    <button onClick={() => handleDelete(m)} title="Delete" className="p-1.5 rounded hover:bg-red-100 text-red-500 transition">
                      <Trash2 size={15} />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
            {filteredMembers.length === 0 && (
              <tr><td colSpan={4} className="p-8 text-center text-gray-400 italic">No members 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">
            <div className="flex justify-between items-center p-6 border-b">
              <h3 className="text-lg font-bold text-blue-900">Edit BNP Member</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="Business Phone" value={editForm.phone} onChange={e => setEditForm({...editForm, phone: e.target.value})} />
              <input className="border p-3 rounded" placeholder="Company Name" value={editForm.company} onChange={e => setEditForm({...editForm, company: e.target.value})} />
              <input className="border p-3 rounded col-span-2" placeholder="Business Category" value={editForm.category} onChange={e => setEditForm({...editForm, category: e.target.value})} />
              <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-blue-600 text-white p-3 rounded-lg font-bold hover:bg-blue-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 MemberAdmin;
