"use client";

import { useState } from "react";
import { siteConfig } from "@/lib/config";

type Category = { id: string; name: string };

export function SellForm({ categories }: { categories: Category[] }) {
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [done, setDone] = useState(false);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);
    setSubmitting(true);
    try {
      const formData = new FormData(e.currentTarget);
      const res = await fetch("/api/sell-requests", {
        method: "POST",
        body: formData,
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error ?? "Could not submit your request.");
        setSubmitting(false);
        return;
      }
      setDone(true);
    } catch {
      setError("Network error. Please try again.");
      setSubmitting(false);
    }
  }

  if (done) {
    return (
      <div className="rounded-xl border border-emerald-200 bg-emerald-50 p-8 text-center">
        <p className="text-4xl">✅</p>
        <h2 className="mt-3 text-xl font-bold text-emerald-900">
          Request received!
        </h2>
        <p className="mt-2 text-sm text-emerald-800">
          Thanks! Our team will review the details and contact you with a quote
          shortly. For a faster response, message us on WhatsApp.
        </p>
        <a
          href={`https://wa.me/${siteConfig.whatsapp}`}
          target="_blank"
          rel="noopener noreferrer"
          className="mt-4 inline-block rounded-lg bg-[#25D366] px-5 py-2.5 text-sm font-semibold text-white hover:bg-[#20bd5a]"
        >
          💬 Message us on WhatsApp
        </a>
      </div>
    );
  }

  const inputClass =
    "mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm";
  const labelClass = "text-sm font-medium text-slate-600";

  return (
    <form
      onSubmit={handleSubmit}
      className="space-y-5 rounded-xl border border-slate-200 bg-white p-6"
    >
      {error ? (
        <div className="rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-700">
          {error}
        </div>
      ) : null}

      <div className="grid gap-4 sm:grid-cols-2">
        <label className="block">
          <span className={labelClass}>Your name *</span>
          <input name="name" required className={inputClass} />
        </label>
        <label className="block">
          <span className={labelClass}>Phone *</span>
          <input name="phone" required placeholder="Mobile number" className={inputClass} />
        </label>
        <label className="block sm:col-span-2">
          <span className={labelClass}>Email (optional)</span>
          <input name="email" type="email" className={inputClass} />
        </label>
      </div>

      <div className="border-t border-slate-100 pt-4">
        <div className="grid gap-4 sm:grid-cols-2">
          <label className="block">
            <span className={labelClass}>Device type</span>
            <select name="categoryId" defaultValue="" className={inputClass}>
              <option value="">Select category</option>
              {categories.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name}
                </option>
              ))}
            </select>
          </label>
          <label className="block">
            <span className={labelClass}>Brand</span>
            <input name="brand" placeholder="e.g. Dell, HP, Apple" className={inputClass} />
          </label>
          <label className="block">
            <span className={labelClass}>Model</span>
            <input name="model" placeholder="e.g. Latitude 7490" className={inputClass} />
          </label>
          <label className="block">
            <span className={labelClass}>Expected price (₹)</span>
            <input
              name="expectedPrice"
              type="number"
              min={0}
              placeholder="Optional"
              className={inputClass}
            />
          </label>
        </div>

        <label className="mt-4 block">
          <span className={labelClass}>Condition & details</span>
          <textarea
            name="conditionNotes"
            rows={4}
            placeholder="Age, working condition, any issues, accessories included, bill/box available…"
            className={inputClass}
          />
        </label>

        <label className="mt-4 block">
          <span className={labelClass}>Photos (up to 6)</span>
          <input
            type="file"
            name="photos"
            accept="image/*"
            multiple
            className="mt-1 block w-full text-sm text-slate-500 file:mr-3 file:rounded-lg file:border-0 file:bg-brand-50 file:px-4 file:py-2 file:text-sm file:font-semibold file:text-brand-700 hover:file:bg-brand-100"
          />
          <span className="mt-1 block text-xs text-slate-400">
            Clear photos help us give an accurate quote faster.
          </span>
        </label>
      </div>

      <button
        type="submit"
        disabled={submitting}
        className="w-full rounded-lg bg-accent-600 py-3 text-sm font-semibold text-white hover:bg-accent-500 disabled:opacity-60"
      >
        {submitting ? "Submitting…" : "Get my quote"}
      </button>
    </form>
  );
}
