import { useEffect, useState } from 'react'
import api from '../api/client'
import { Plus, Trash2, Edit2, X, Check } from 'lucide-react'

export default function Customers() {
  const [customers, setCustomers] = useState([])
  const [loading, setLoading] = useState(true)
  const [showAdd, setShowAdd] = useState(false)
  const [editId, setEditId] = useState(null)
  const [form, setForm] = useState({ number: '', name: '' })

  const reload = () => {
    api.getCustomers().then((c) => setCustomers(c || [])).finally(() => setLoading(false))
  }

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

  const handleAdd = async () => {
    if (!form.number || !form.name) return
    await api.createCustomer(form.number, form.name)
    setForm({ number: '', name: '' })
    setShowAdd(false)
    reload()
  }

  const handleUpdate = async (id) => {
    await api.updateCustomer(id, form.number, form.name)
    setEditId(null)
    reload()
  }

  const handleDelete = async (id) => {
    if (!confirm('Kunde wirklich loeschen?')) return
    await api.deleteCustomer(id)
    reload()
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold text-white">Kunden</h1>
        <button
          onClick={() => { setShowAdd(true); setForm({ number: '', name: '' }) }}
          className="flex items-center gap-1.5 px-3 py-1.5 bg-orange-600 hover:bg-orange-700 rounded text-sm text-white transition-colors"
        >
          <Plus className="w-4 h-4" />
          Neuer Kunde
        </button>
      </div>

      <div className="bg-gray-900 rounded-lg border border-gray-800 overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-gray-800 text-left text-gray-500">
              <th className="px-4 py-2 font-medium">Nummer</th>
              <th className="px-4 py-2 font-medium">Name</th>
              <th className="px-4 py-2 font-medium hidden md:table-cell">Erstellt</th>
              <th className="px-4 py-2 font-medium w-24"></th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-800">
            {showAdd && (
              <tr>
                <td className="px-4 py-2">
                  <input
                    type="text"
                    placeholder="K05116"
                    value={form.number}
                    onChange={(e) => setForm({ ...form, number: e.target.value })}
                    className="w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-white text-sm focus:outline-none focus:border-orange-500"
                    autoFocus
                  />
                </td>
                <td className="px-4 py-2">
                  <input
                    type="text"
                    placeholder="Kundenname"
                    value={form.name}
                    onChange={(e) => setForm({ ...form, name: e.target.value })}
                    className="w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-white text-sm focus:outline-none focus:border-orange-500"
                  />
                </td>
                <td className="hidden md:table-cell"></td>
                <td className="px-4 py-2">
                  <div className="flex gap-1">
                    <button onClick={handleAdd} className="text-green-400 hover:text-green-300">
                      <Check className="w-4 h-4" />
                    </button>
                    <button onClick={() => setShowAdd(false)} className="text-gray-500 hover:text-gray-300">
                      <X className="w-4 h-4" />
                    </button>
                  </div>
                </td>
              </tr>
            )}
            {customers.map((c) => (
              <tr key={c.id} className="hover:bg-gray-800/50">
                {editId === c.id ? (
                  <>
                    <td className="px-4 py-2">
                      <input
                        type="text"
                        value={form.number}
                        onChange={(e) => setForm({ ...form, number: e.target.value })}
                        className="w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-white text-sm focus:outline-none focus:border-orange-500"
                      />
                    </td>
                    <td className="px-4 py-2">
                      <input
                        type="text"
                        value={form.name}
                        onChange={(e) => setForm({ ...form, name: e.target.value })}
                        className="w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-white text-sm focus:outline-none focus:border-orange-500"
                      />
                    </td>
                    <td className="hidden md:table-cell"></td>
                    <td className="px-4 py-2">
                      <div className="flex gap-1">
                        <button onClick={() => handleUpdate(c.id)} className="text-green-400 hover:text-green-300">
                          <Check className="w-4 h-4" />
                        </button>
                        <button onClick={() => setEditId(null)} className="text-gray-500 hover:text-gray-300">
                          <X className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </>
                ) : (
                  <>
                    <td className="px-4 py-2 text-orange-400 font-mono">{c.number}</td>
                    <td className="px-4 py-2 text-white">{c.name}</td>
                    <td className="px-4 py-2 text-gray-500 text-xs hidden md:table-cell">
                      {new Date(c.created_at).toLocaleDateString('de-DE')}
                    </td>
                    <td className="px-4 py-2">
                      <div className="flex gap-1">
                        <button
                          onClick={() => { setEditId(c.id); setForm({ number: c.number, name: c.name }) }}
                          className="text-gray-500 hover:text-gray-300"
                        >
                          <Edit2 className="w-4 h-4" />
                        </button>
                        <button onClick={() => handleDelete(c.id)} className="text-gray-500 hover:text-red-400">
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </>
                )}
              </tr>
            ))}
          </tbody>
        </table>
        {!loading && customers.length === 0 && !showAdd && (
          <div className="text-center py-8 text-gray-500">Keine Kunden angelegt</div>
        )}
      </div>
    </div>
  )
}
