import React, { useEffect, useState } from 'react';
import api from '../hooks/api';
import Modal from '../components/Modal';
import ConfirmDialog from '../components/ConfirmDialog';

const init = { name:'', email:'', phone:'', address:'', company:'', contact_person:'' };

export default function Customers() {
  const [customers, setCustomers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [selectedId, setSelectedId] = useState(null);
  const [form, setForm] = useState(init);
  const [editing, setEditing] = useState(false);
  const [search, setSearch] = useState('');

  const load = async () => { setLoading(true); const {data}=await api.get('/api/customers'); setCustomers(data); setLoading(false); };
  useEffect(()=>{load();},[]);

  const openAdd = () => { setForm(init); setEditing(false); setModalOpen(true); };
  const openEdit = c => { setForm(c); setEditing(true); setSelectedId(c.id||c._id); setModalOpen(true); };

  const handleSubmit = async e => {
    e.preventDefault();
    if (editing) await api.put(`/api/customers/${selectedId}`, form);
    else await api.post('/api/customers', form);
    setModalOpen(false); load();
  };

  const f = c => c.filter(x=>x.name?.toLowerCase().includes(search.toLowerCase())||x.company?.toLowerCase().includes(search.toLowerCase()));

  return (
    <div>
      <div className="page-header">
        <h1 className="page-title">Customers</h1>
        <button className="btn-primary" onClick={openAdd}>+ Add Customer</button>
      </div>
      <div className="card">
        <div className="mb-4"><input className="input-field max-w-sm" placeholder="Search customers..." value={search} onChange={e=>setSearch(e.target.value)} /></div>
        <div className="overflow-x-auto">
          {loading ? <div className="text-center py-10"><div className="animate-spin inline-block rounded-full h-8 w-8 border-b-2 border-blue-600"></div></div> : (
            <table className="w-full">
              <thead><tr>
                <th className="table-header text-left">Name</th>
                <th className="table-header text-left">Company</th>
                <th className="table-header text-left">Email</th>
                <th className="table-header text-left">Phone</th>
                <th className="table-header text-left">Contact Person</th>
                <th className="table-header text-left">Address</th>
                <th className="table-header text-left">Actions</th>
              </tr></thead>
              <tbody>
                {f(customers).map(c=>(
                  <tr key={c.id||c._id} className="table-row">
                    <td className="table-cell font-semibold">{c.name}</td>
                    <td className="table-cell">{c.company||'—'}</td>
                    <td className="table-cell">{c.email||'—'}</td>
                    <td className="table-cell">{c.phone}</td>
                    <td className="table-cell">{c.contact_person||'—'}</td>
                    <td className="table-cell max-w-xs truncate">{c.address||'—'}</td>
                    <td className="table-cell">
                      <div className="flex gap-2">
                        <button onClick={()=>openEdit(c)} className="text-blue-600 hover:text-blue-800 text-sm font-medium">Edit</button>
                        <button onClick={()=>{setSelectedId(c.id||c._id);setConfirmOpen(true);}} className="text-red-600 hover:text-red-800 text-sm font-medium">Delete</button>
                      </div>
                    </td>
                  </tr>
                ))}
                {!f(customers).length && <tr><td colSpan={7} className="text-center py-10 text-gray-400">No customers found</td></tr>}
              </tbody>
            </table>
          )}
        </div>
      </div>
      <Modal isOpen={modalOpen} onClose={()=>setModalOpen(false)} title={editing?'Edit Customer':'Add Customer'} size="lg">
        <form onSubmit={handleSubmit} className="grid grid-cols-2 gap-4">
          {[['name','Full Name'],['company','Company'],['email','Email'],['phone','Phone'],['contact_person','Contact Person']].map(([k,l])=>(
            <div key={k}>
              <label className="block text-sm font-medium text-gray-700 mb-1">{l}</label>
              <input className="input-field" value={form[k]||''} onChange={e=>setForm({...form,[k]:e.target.value})} required={k==='name'||k==='phone'} />
            </div>
          ))}
          <div className="col-span-2">
            <label className="block text-sm font-medium text-gray-700 mb-1">Address</label>
            <textarea className="input-field" rows={2} value={form.address||''} onChange={e=>setForm({...form,address:e.target.value})} />
          </div>
          <div className="col-span-2 flex gap-3 justify-end mt-2">
            <button type="button" className="btn-secondary" onClick={()=>setModalOpen(false)}>Cancel</button>
            <button type="submit" className="btn-primary">{editing?'Update':'Add Customer'}</button>
          </div>
        </form>
      </Modal>
      <ConfirmDialog isOpen={confirmOpen} onClose={()=>setConfirmOpen(false)} onConfirm={async()=>{await api.delete(`/api/customers/${selectedId}`);load();}} />
    </div>
  );
}
