import { useEffect, useState } from 'react';
import api from '../api/axios';
import PageHeader, { FormCard, Field, Alert, DataTable } from '../components/PageUI';

const initialForm = {
  supplierCode: '',
  supplierName: '',
  telephone: '',
  address: '',
  email: '',
};

export default function Supplier() {
  const [form, setForm] = useState(initialForm);
  const [suppliers, setSuppliers] = useState([]);
  const [editMode, setEditMode] = useState(false);
  const [message, setMessage] = useState({ type: '', text: '' });
  const [loading, setLoading] = useState(false);

  const fetchSuppliers = async () => {
    try {
      const { data } = await api.get('/suppliers');
      setSuppliers(data);
    } catch {
      setMessage({ type: 'error', text: 'Failed to load suppliers' });
    }
  };

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

  const handleChange = (e) => setForm({ ...form, [e.target.name]: e.target.value });

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setMessage({ type: '', text: '' });
    try {
      if (editMode) {
        await api.put(`/suppliers/${form.supplierCode}`, form);
        setMessage({ type: 'success', text: 'Supplier updated' });
      } else {
        await api.post('/suppliers', form);
        setMessage({ type: 'success', text: 'Supplier added' });
      }
      setForm(initialForm);
      setEditMode(false);
      fetchSuppliers();
    } catch (err) {
      setMessage({ type: 'error', text: err.response?.data?.message || 'Operation failed' });
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (s) => {
    setForm({ supplierCode: s.supplierCode, supplierName: s.supplierName, telephone: s.telephone, address: s.address, email: s.email });
    setEditMode(true);
  };

  const handleDelete = async (row) => {
    if (!window.confirm('Delete this supplier?')) return;
    try {
      await api.delete(`/suppliers/${row.supplierCode}`);
      setMessage({ type: 'success', text: 'Supplier deleted' });
      fetchSuppliers();
    } catch (err) {
      setMessage({ type: 'error', text: err.response?.data?.message || 'Delete failed' });
    }
  };

  return (
    <>
      <PageHeader description="Manage supplier records and contact details." />
      <div className="grid gap-5 xl:grid-cols-5">
        <div className="xl:col-span-2">
          <FormCard
            title={editMode ? 'Update Supplier' : 'Add Supplier'}
            editMode={editMode}
            onSubmit={handleSubmit}
            footer={
              <>
                <button type="submit" disabled={loading} className="btn-primary">
                  {loading ? 'Saving...' : editMode ? 'Update' : 'Add Supplier'}
                </button>
                {editMode && (
                  <button type="button" onClick={() => { setForm(initialForm); setEditMode(false); }} className="btn-secondary">Cancel</button>
                )}
              </>
            }
          >
            <Field label="Supplier Code">
              <input name="supplierCode" value={form.supplierCode} onChange={handleChange} className="input-field" required readOnly={editMode} />
            </Field>
            <Field label="Supplier Name">
              <input name="supplierName" value={form.supplierName} onChange={handleChange} className="input-field" required />
            </Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="Telephone">
                <input name="telephone" value={form.telephone} onChange={handleChange} className="input-field" required />
              </Field>
              <Field label="Email">
                <input type="email" name="email" value={form.email} onChange={handleChange} className="input-field" required />
              </Field>
            </div>
            <Field label="Address">
              <input name="address" value={form.address} onChange={handleChange} className="input-field" required />
            </Field>
            <Alert type={message.type} message={message.text} />
          </FormCard>
        </div>

        <div className="xl:col-span-3">
          <DataTable
            title="Registered Suppliers"
            count={suppliers.length}
            columns={[
              { key: 'supplierCode', label: 'Code', bold: true },
              { key: 'supplierName', label: 'Name' },
              { key: 'telephone', label: 'Phone' },
              { key: 'email', label: 'Email' },
            ]}
            data={suppliers}
            onEdit={handleEdit}
            onDelete={handleDelete}
          />
        </div>
      </div>
    </>
  );
}
