import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import axios from 'axios'

function Supplier() {

  const [suppliers, setSuppliers] = useState([])
  const [supplierName, setSupplierName] = useState('')
  const [address, setAddress] = useState('')
  const [telephone, setTelephone] = useState('')
  const [registrationDate, setRegistrationDate] = useState('')
  const [editId, setEditId] = useState(null)
  const [message, setMessage] = useState('')

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

  const clearForm = () => {
    setSupplierName('')
    setAddress('')
    setTelephone('')
    setRegistrationDate('')
    setEditId(null)
  }

  const handleGet = async () => {
    try {
      const res = await axios.get(
        'http://localhost:5001/api/suppliers/getsupplier',
        { headers }
      )

      setSuppliers(res.data)

    } catch (error) {
      console.log(error)
    }
  }

  useEffect(() => {
    handleGet()
  }, [])

  const handleSubmit = async (e) => {
    e.preventDefault()

    try {

      if (editId) {

await axios.put(
  `http://localhost:5001/api/suppliers/updatesupplier/${editId}`,
  { supplierName, address, telephone, registrationDate },
  { headers }
)

        setMessage('Updated successfully')

      } else {

await axios.post(
  'http://localhost:5001/api/suppliers/addsupplier',
  { supplierName, address, telephone, registrationDate },
  { headers }
)

        setMessage('Added successfully')
      }

      clearForm()
      handleGet()

    } catch (error) {
      console.log(error)
      setMessage('Something went wrong')
    }
  }

  const handleDelete = async (id) => {
    try {

      await axios.delete(
        `http://localhost:5001/api/suppliers/deletesupplier/${id}`,
        { headers }
      )

      handleGet()

    } catch (error) {
      console.log(error)
    }
  }

  const handleEdit = (supplier) => {
    setSupplierName(supplier.supplierName)
    setAddress(supplier.address)
    setTelephone(supplier.telephone)
    setRegistrationDate(supplier.registrationDate)
    setEditId(supplier._id)
  }

  return (
    <div className="max-w-2xl mx-auto p-4">

      <div className='mt-3 mb-6'>
        <Link
          to="/dashboard"
          className="font-medium hover:text-white border border-slate-600 rounded-lg px-3 py-2 hover:bg-slate-800 transition-colors"
        >
          BACK
        </Link>
      </div>

      <h1 className="text-2xl font-bold mb-4">Supplier Management</h1>

      {message && <p className="mb-3 text-green-600">{message}</p>}

      <form onSubmit={handleSubmit} className="border p-4 rounded space-y-3">

        <input
          type='text'
          placeholder='Supplier Name'
          value={supplierName}
          onChange={(e) => setSupplierName(e.target.value)}
          className="w-full border p-2 rounded"
          required
        />

        <input
          type='text'
          placeholder='Address'
          value={address}
          onChange={(e) => setAddress(e.target.value)}
          className="w-full border p-2 rounded"
          required
        />

        <input
          type='text'
          placeholder='Telephone'
          value={telephone}
          onChange={(e) => setTelephone(e.target.value)}
          className="w-full border p-2 rounded"
          required
        />

        <input
          type='date'
          value={registrationDate}
          onChange={(e) => setRegistrationDate(e.target.value)}
          className="w-full border p-2 rounded"
          required
        />

        <div>
          <button type='submit' className="bg-blue-500 text-white px-4 py-2 rounded">
            {editId ? 'Update' : 'Add'}
          </button>
        </div>

      </form>

      <div className="mt-6 space-y-3">

        {suppliers.map((supplier) => (
          <div key={supplier._id} className="border p-3 rounded">

            <p>Supplier Name: {supplier.supplierName}</p>
            <p>Address: {supplier.address}</p>
            <p>Telephone: {supplier.telephone}</p>
            <p>Registration Date: {supplier.registrationDate}</p>

            <div className="flex gap-3 mt-2">
              <button type='button' onClick={() => handleEdit(supplier)} className="text-blue-500">
                Edit
              </button>

              <button type='button' onClick={() => handleDelete(supplier._id)} className="text-red-500">
                Delete
              </button>
            </div>

          </div>
        ))}

      </div>

    </div>
  )
}

export default Supplier