'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { Pencil, Trash2, Plus, X } from 'lucide-react';
import { toast } from 'sonner';
import { saveProduct, removeProduct } from '@/app/admin/products/actions';
import { formatPrice } from '@/lib/utils';
import type { Product, Category } from '@/types';

export function ProductsClient({
  initialProducts,
  categories,
}: {
  initialProducts: Product[];
  categories: Category[];
}) {
  const router = useRouter();
  const products = initialProducts;
  const [editing, setEditing] = useState<Product | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [status, setStatus] = useState<{ error?: string; success?: boolean } | null>(null);

  function resetForm() {
    setEditing(null);
    setShowForm(false);
    setStatus(null);
  }

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const result = await saveProduct(formData);
    setStatus(result);
    if (result?.success) {
      resetForm();
      router.refresh();
    }
  }

  async function handleDelete(id: string) {
    if (!confirm('Delete this product?')) return;
    const formData = new FormData();
    formData.set('id', id);
    const result = await removeProduct(formData);
    if (result?.error) {
      toast.error(result.error);
    } else {
      toast.success('Product deleted');
      router.refresh();
    }
  }

  const imagesDefault = editing ? editing.images.join('\n') : '';
  const specsDefault = editing
    ? Object.entries(editing.specs ?? {})
        .map(([k, v]) => `${k}: ${v}`)
        .join('\n')
    : '';

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Products</h1>
        <button
          onClick={() => {
            setEditing(null);
            setShowForm(!showForm);
          }}
          className="inline-flex items-center gap-1 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground"
        >
          {showForm ? (
            <>
              <X className="h-4 w-4" /> Close
            </>
          ) : (
            <>
              <Plus className="h-4 w-4" /> Add product
            </>
          )}
        </button>
      </div>

      {showForm && (
        <form
          key={editing?.id || 'new'}
          onSubmit={handleSubmit}
          className="rounded-xl border bg-card p-4"
        >
          {status?.error && (
            <p className="mb-4 rounded-lg bg-destructive/10 p-3 text-sm text-destructive">
              {status.error}
            </p>
          )}
          {status?.success && (
            <p className="mb-4 rounded-lg bg-green-500/10 p-3 text-sm text-green-600">
              Saved
            </p>
          )}

          <input type="hidden" name="id" value={editing?.id || ''} />

          <div className="grid gap-4 md:grid-cols-2">
            <div className="md:col-span-2">
              <label className="text-sm font-medium">Name</label>
              <input
                name="name"
                required
                defaultValue={editing?.name || ''}
                className="mt-1 w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
              />
            </div>

            <div className="md:col-span-2">
              <label className="text-sm font-medium">Description</label>
              <textarea
                name="description"
                rows={3}
                defaultValue={editing?.description || ''}
                className="mt-1 w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
              />
            </div>

            <div>
              <label className="text-sm font-medium">Price (KES)</label>
              <input
                name="price"
                type="number"
                min="0"
                step="0.01"
                required
                defaultValue={editing?.price ?? ''}
                className="mt-1 w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
              />
            </div>

            <div>
              <label className="text-sm font-medium">Compare price (optional)</label>
              <input
                name="comparePrice"
                type="number"
                min="0"
                step="0.01"
                defaultValue={editing?.comparePrice ?? ''}
                className="mt-1 w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
              />
            </div>

            <div>
              <label className="text-sm font-medium">Stock</label>
              <input
                name="stock"
                type="number"
                min="0"
                required
                defaultValue={editing?.stock ?? 0}
                className="mt-1 w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
              />
            </div>

            <div>
              <label className="text-sm font-medium">Category</label>
              <select
                name="categoryId"
                required
                defaultValue={editing?.categoryId || ''}
                className="mt-1 w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
              >
                <option value="">Select category</option>
                {categories.map((c) => (
                  <option key={c.id} value={c.id}>
                    {c.name}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="text-sm font-medium">Status</label>
              <select
                name="status"
                defaultValue={editing?.status || 'active'}
                className="mt-1 w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
              >
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
              </select>
            </div>

            <div className="flex items-center gap-2 pt-6">
              <input
                name="isFeatured"
                type="checkbox"
                defaultChecked={editing?.isFeatured || false}
                className="h-4 w-4"
              />
              <label className="text-sm font-medium">Featured on home</label>
            </div>

            <div className="md:col-span-2">
              <label className="text-sm font-medium">
                Image URLs (one per line)
              </label>
              <textarea
                name="images"
                rows={3}
                defaultValue={imagesDefault}
                placeholder="/placeholder.svg"
                className="mt-1 w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
              />
            </div>

            <div className="md:col-span-2">
              <label className="text-sm font-medium">
                Specifications (key: value, one per line)
              </label>
              <textarea
                name="specs"
                rows={3}
                defaultValue={specsDefault}
                placeholder="brand: Samsung\nbattery: 5000mAh"
                className="mt-1 w-full rounded-lg border bg-background px-3 py-2 outline-none focus:ring-2 focus:ring-ring"
              />
            </div>
          </div>

          <div className="mt-4 flex items-center gap-2">
            <button
              type="submit"
              className="inline-flex items-center gap-1 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground"
            >
              <Plus className="h-4 w-4" />
              {editing ? 'Update' : 'Add'} product
            </button>
            <button
              type="button"
              onClick={resetForm}
              className="rounded-lg border px-4 py-2 text-sm"
            >
              Cancel
            </button>
          </div>
        </form>
      )}

      <div className="overflow-hidden rounded-xl border bg-card">
        <table className="w-full text-left text-sm">
          <thead className="border-b bg-muted/50 text-muted-foreground">
            <tr>
              <th className="px-4 py-3 font-medium">Image</th>
              <th className="px-4 py-3 font-medium">Name</th>
              <th className="px-4 py-3 font-medium">Category</th>
              <th className="px-4 py-3 font-medium">Price</th>
              <th className="px-4 py-3 font-medium">Stock</th>
              <th className="px-4 py-3 font-medium">Status</th>
              <th className="px-4 py-3 font-medium"></th>
            </tr>
          </thead>
          <tbody>
            {products.map((p) => (
              <tr key={p.id} className="border-b last:border-0">
                <td className="px-4 py-3">
                  <div className="relative h-12 w-12 overflow-hidden rounded-md bg-muted">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img
                      src={p.images[0] || '/placeholder.svg'}
                      alt={p.name}
                      className="h-full w-full object-cover"
                    />
                  </div>
                </td>
                <td className="px-4 py-3 font-medium">
                  <Link
                    href={`/products/${p.slug}`}
                    target="_blank"
                    className="hover:underline"
                  >
                    {p.name}
                  </Link>
                </td>
                <td className="px-4 py-3 text-muted-foreground">
                  {p.category?.name || '-'}
                </td>
                <td className="px-4 py-3">{formatPrice(p.price)}</td>
                <td className="px-4 py-3">{p.stock}</td>
                <td className="px-4 py-3 capitalize">{p.status}</td>
                <td className="px-4 py-3">
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => {
                        setEditing(p);
                        setShowForm(true);
                        window.scrollTo({ top: 0, behavior: 'smooth' });
                      }}
                      className="rounded-md p-2 hover:bg-muted"
                    >
                      <Pencil className="h-4 w-4" />
                    </button>
                    <button
                      onClick={() => handleDelete(p.id)}
                      className="rounded-md p-2 text-destructive hover:bg-destructive/10"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
