import { useEffect, useState } from 'react';
import api from '../api';

export default function CustomerPage() {
  const [customers, setCustomers] = useState([]);
  const [form, setForm] = useState({ customerNumber: '', firstName: '', lastName: '', telephone: '', address: '' });
  const [message, setMessage] = useState('');
  const [editingId, setEditingId] = useState(null);


  const fetchCustomers = async () => {
    try {
      const response = await api.get('/customers');
      setCustomers(response.data);
    } catch (error) {
      console.error(error);
    }
  };

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    try {
      if (editingId) {
        await api.put(`/customers/${editingId}`, form);
        setMessage('Customer updated successfully');
        setEditingId(null);
      } else {
        await api.post('/customers', form);
        setMessage('Customer added successfully');
      }

      setForm({ customerNumber: '', firstName: '', lastName: '', telephone: '', address: '' });
      fetchCustomers();
    } catch (error) {
      setMessage(error.response?.data?.message || 'Unable to save customer.');
    }
  };

  const handleEdit = (customer) => {
    setEditingId(customer._id);
    setForm({
      customerNumber: customer.customerNumber,
      firstName: customer.firstName,
      lastName: customer.lastName,
      telephone: customer.telephone,
      address: customer.address,
    });
    setMessage('Editing customer record. Click save to update.');
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this customer?')) return;
    try {
      await api.delete(`/customers/${id}`);
      setMessage('Customer deleted successfully');
      fetchCustomers();
    } catch (error) {
      setMessage(error.response?.data?.message || 'Unable to delete customer.');
    }
  };

  return (
    <div className="space-y-6">
      <section className="rounded-3xl bg-white p-6 shadow-[0_10px_25px_rgba(15,23,42,0.10)] shadow-slate-200">
        <h2 className="text-xl font-semibold text-slate-900">Add Customer</h2>
        <form onSubmit={handleSubmit} className="mt-5 grid gap-4 sm:grid-cols-2">
          <input
            placeholder="Customer Number"
            value={form.customerNumber}
            onChange={(e) => setForm({ ...form, customerNumber: e.target.value })}
            required
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          />
          <input
            placeholder="First Name"
            value={form.firstName}
            onChange={(e) => setForm({ ...form, firstName: e.target.value })}
            required
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          />
          <input
            placeholder="Last Name"
            value={form.lastName}
            onChange={(e) => setForm({ ...form, lastName: e.target.value })}
            required
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          />
          <input
            placeholder="Telephone"
            value={form.telephone}
            onChange={(e) => setForm({ ...form, telephone: e.target.value })}
            required
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          />
          <input
            placeholder="Address"
            value={form.address}
            onChange={(e) => setForm({ ...form, address: e.target.value })}
            required
            className="col-span-full rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          />
          <button className="col-span-full rounded-2xl bg-slate-900 px-5 py-3 text-white hover:bg-slate-800" type="submit">
            {editingId ? 'Update Customer' : 'Save Customer'}
          </button>
        </form>
        {message && <p className="mt-4 text-sm text-emerald-600">{message}</p>}
      </section>

      <section className="rounded-3xl bg-white p-6 shadow-[0_10px_25px_rgba(15,23,42,0.10)] shadow-slate-200">
        <h2 className="text-xl font-semibold text-slate-900">Customer List</h2>
        <div className="mt-4 overflow-x-auto">
          <table className="w-full min-w-max divide-y divide-slate-200 text-left text-sm text-slate-700">
            <thead className="bg-slate-50">
              <tr>
                <th className="px-4 py-3">Customer No</th>
                <th className="px-4 py-3">Name</th>
                <th className="px-4 py-3">Telephone</th>
                <th className="px-4 py-3">Address</th>
                <th className="px-4 py-3">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-200">
              {customers.map((customer) => (
                <tr key={customer._id}>
                  <td className="px-4 py-3">{customer.customerNumber}</td>
                  <td className="px-4 py-3">{customer.firstName} {customer.lastName}</td>
                  <td className="px-4 py-3">{customer.telephone}</td>
                  <td className="px-4 py-3">{customer.address}</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <button
                        type="button"
                        onClick={() => handleEdit(customer)}
                        className="rounded-full bg-amber-500 px-3 py-1 text-sm font-semibold text-slate-950 hover:bg-amber-400"
                      >
                        Edit
                      </button>
                      <button
                        type="button"
                        onClick={() => handleDelete(customer._id)}
                        className="rounded-full bg-red-500 px-3 py-1 text-sm font-semibold text-white hover:bg-red-400"
                      >
                        Delete
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
}
