import { useState } from "react"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { api } from "../lib/api"

export default function Customers() {
  const queryClient = useQueryClient()
  const [name, setName] = useState("")

  const { data: customers, isLoading, isError } = useQuery({
    queryKey: ["customers"],
    queryFn: () => api.listCustomers()
  })

  const createMutation = useMutation({
    mutationFn: (name: string) => api.createCustomer({ name }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["customers"] })
      setName("")
    }
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => api.deleteCustomer(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["customers"] })
    }
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!name.trim()) return
    createMutation.mutate(name)
  }

  if (isLoading) return <div className="p-6 text-gray-500">Loading customers...</div>
  if (isError) return <div className="p-6 text-red-500">Error loading customers.</div>

  return (
    <div className="p-6 max-w-6xl mx-auto space-y-8">
      <header>
        <h1 className="text-2xl font-bold text-gray-900">Customers</h1>
        <p className="text-gray-500">Manage your client database</p>
      </header>

      <section className="bg-white p-6 rounded-lg border border-gray-200 shadow-sm">
        <h2 className="text-lg font-semibold mb-4">Add New Customer</h2>
        <form onSubmit={handleSubmit} className="flex gap-4">
          <div className="flex-1">
            <label className="block text-sm font-medium text-gray-700 mb-1">Customer Name</label>
            <input
              type="text"
              required
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 outline-none"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Enter company or person name"
            />
          </div>
          <div className="flex items-end">
            <button
              type="submit"
              disabled={createMutation.isPending}
              className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition-colors disabled:bg-blue-300 font-medium"
            >
              {createMutation.isPending ? "Saving..." : "Add Customer"}
            </button>
          </div>
        </form>
      </section>

      <section className="overflow-x-auto bg-white rounded-lg border border-gray-200 shadow-sm">
        <table className="w-full text-left border-collapse">
          <thead>
            <tr className="bg-gray-50 border-b border-gray-200">
              <th className="px-6 py-3 text-sm font-semibold text-gray-600">Name</th>
              <th className="px-6 py-3 text-sm font-semibold text-gray-600 text-right">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {customers && customers.length > 0 ? (
              customers.map((customer: any) => (
                <tr key={customer.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-6 py-4 text-sm text-gray-900">{customer.name}</td>
                  <td className="px-6 py-4 text-right">
                    <button
                      onClick={() => {
                        if (confirm("Are you sure you want to delete this customer?")) {
                          deleteMutation.mutate(customer.id)
                        }
                      }}
                      disabled={deleteMutation.isPending}
                      className="text-red-600 hover:text-red-800 text-sm font-medium disabled:text-gray-400"
                    >
                      Delete
                    </button>
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={2} className="px-6 py-10 text-center text-gray-500">
                  No customers found. Add your first customer above.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </section>
    </div>
  )
}