import React, { useEffect, useState } from 'react';
import axios from 'axios';

function Customer() {
  const [customers, setCustomers] = useState([]);
  const [customerNumber, setCustomerNumber] = useState('');
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [telephone, setTelephone] = useState('');
  const [address, setAddress] = useState('');
  const [message, setMessage] = useState('');

  const headers = {
    Authorization: `Bearer ${localStorage.getItem('token')}`,
  };

  const clearForm = () => {
    setCustomerNumber('');
    setFirstName('');
    setLastName('');
    setTelephone('');
    setAddress('');
  };

  const fetchCustomers = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/customer/getcustomers', { headers });
      setCustomers(res.data);
    } catch (err) {
      console.error(err);
      setMessage('Unable to load customers');
    }
  };

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    setMessage('');

    try {
      await axios.post(
        'http://localhost:5001/api/customer/addcustomer',
        { customerNumber, firstName, lastName, telephone, address },
        { headers }
      );

      setMessage('Customer saved successfully');
      clearForm();
      fetchCustomers();
    } catch (err) {
      console.error(err);
      setMessage(err.response?.data?.message || 'Failed to save customer');
    }
  };

  return (
    <div className="max-w-2xl">
      <h1 className="text-xl font-semibold text-brand-900 mb-1">Customers</h1>
      <p className="text-sm text-slate-500 mb-6">Add and manage customer records.</p>

      {message && (
        <p className={`mb-4 text-sm ${message.includes('success') ? 'alert-success' : 'alert-error'}`}>
          {message}
        </p>
      )}

      <form onSubmit={handleSubmit} className="card p-5 space-y-3 mb-8">
        <input
          type="text"
          placeholder="Customer Number"
          value={customerNumber}
          onChange={(e) => setCustomerNumber(e.target.value)}
          className="input"
          required
        />
        <div className="grid gap-3 sm:grid-cols-2">
          <input
            type="text"
            placeholder="First Name"
            value={firstName}
            onChange={(e) => setFirstName(e.target.value)}
            className="input"
            required
          />
          <input
            type="text"
            placeholder="Last Name"
            value={lastName}
            onChange={(e) => setLastName(e.target.value)}
            className="input"
            required
          />
        </div>
        <input
          type="text"
          placeholder="Telephone"
          value={telephone}
          onChange={(e) => setTelephone(e.target.value)}
          className="input"
          required
        />
        <textarea
          placeholder="Address"
          value={address}
          onChange={(e) => setAddress(e.target.value)}
          className="input resize-none"
          rows="3"
          required
        />
        <button type="submit" className="btn-primary">
          Add Customer
        </button>
      </form>

      <h2 className="text-sm font-medium text-slate-600 mb-3">Saved customers</h2>
      {customers.length === 0 ? (
        <p className="text-sm text-slate-500">No customer records yet.</p>
      ) : (
        <div className="space-y-3">
          {customers.map((customer) => (
            <div key={customer._id} className="card p-4">
              <p className="text-xs text-slate-500">#{customer.customerNumber}</p>
              <p className="font-medium text-brand-900">
                {customer.firstName} {customer.lastName}
              </p>
              <p className="text-sm text-slate-600 mt-1">{customer.telephone}</p>
              <p className="text-sm text-slate-600">{customer.address}</p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default Customer;
