"use client";

import { useState } from "react";
import Link from "next/link";
import { Loader2, CheckCircle2, UserCircle2 } from "lucide-react";
import { formsApi } from "@/lib/api/forms";
import { customerApi } from "@/lib/api/customer";
import { ApiException } from "@/lib/api/client";
import { useToken } from "@/lib/auth/useToken";

type Props = {
  productId?: number;
  productName: string;
};

type Form = { quantity: string; company: string; phone: string; email: string; name: string; description: string };

export default function QuoteForm({ productId, productName }: Props) {
  const { token, ready } = useToken();
  const isAuthed = ready && !!token;

  const [form, setForm] = useState<Form>({ quantity: "", company: "", phone: "", email: "", name: "", description: "" });
  const [loading, setLoading] = useState(false);
  const [done, setDone] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      if (isAuthed && token && productId) {
        const res = await customerApi.createEnquiry(token, {
          commodity_product_id: productId,
          quantity: form.quantity || undefined,
          description: form.description || undefined,
          origin_city: form.company || undefined,
        });
        setDone(res.data.unique_id ?? "submitted");
      } else {
        const res = await formsApi.enquiry({
          name: form.name.trim() || form.company.trim() || "Buyer",
          email: form.email.trim() || `noemail+${Date.now()}@biznie.placeholder`,
          contact_number: form.phone.trim(),
          company_name: form.company.trim() || undefined,
          requirement: `Product: ${productName}${productId ? ` (#${productId})` : ""} | Quantity: ${form.quantity}${form.description ? ` | ${form.description}` : ""}`,
        });
        setDone(res.data.reference);
      }
    } catch (err) {
      if (err instanceof ApiException) setError(err.message);
      else setError("Could not submit. Please try again.");
    } finally {
      setLoading(false);
    }
  }

  if (done) {
    return (
      <div className="text-center py-6">
        <div className="w-14 h-14 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-3">
          <CheckCircle2 size={28} className="text-green-600" />
        </div>
        <h4 className="font-bold text-gray-900 mb-1">Quote Requested!</h4>
        <p className="text-xs text-gray-500">Reference: <span className="font-mono font-semibold">{done}</span></p>
        {isAuthed ? (
          <p className="text-xs text-gray-500 mt-2">
            Track this in <Link href="/rfq" className="text-[#CC1414] font-semibold hover:underline">My Enquiries</Link>.
          </p>
        ) : (
          <p className="text-xs text-gray-400 mt-2">Our team will reach out within 2 hours.</p>
        )}
      </div>
    );
  }

  const inputCls =
    "w-full px-4 py-3 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-[#CC1414]/20 focus:border-[#CC1414]";

  return (
    <form onSubmit={onSubmit} className="space-y-3">
      {error && <div className="rounded-lg bg-red-50 border border-red-100 px-3 py-2 text-xs text-red-700">{error}</div>}

      {isAuthed ? (
        <div className="flex items-center gap-2 rounded-lg bg-emerald-50 border border-emerald-100 px-3 py-2 text-xs text-emerald-700">
          <UserCircle2 size={14} /> Signed in — this enquiry will be saved to your dashboard.
        </div>
      ) : (
        <div className="rounded-lg bg-blue-50 border border-blue-100 px-3 py-2 text-xs text-blue-700">
          <Link href={`/login?redirect=/products`} className="font-semibold hover:underline">Sign in</Link> to track your enquiries.
        </div>
      )}

      {!isAuthed && (
        <>
          <input type="text" required placeholder="Your name" value={form.name}
            onChange={(e) => setForm({ ...form, name: e.target.value })} className={inputCls} />
          <input type="email" placeholder="Email (optional)" value={form.email}
            onChange={(e) => setForm({ ...form, email: e.target.value })} className={inputCls} />
          <div className="flex">
            <span className="inline-flex items-center px-3 border border-r-0 border-gray-200 rounded-l-xl bg-gray-50 text-sm text-gray-500">🇮🇳 +91</span>
            <input type="tel" required placeholder="Mobile number" inputMode="numeric" value={form.phone}
              onChange={(e) => setForm({ ...form, phone: e.target.value.replace(/\D/g, "").slice(0, 10) })}
              className={`${inputCls} rounded-l-none flex-1`} />
          </div>
        </>
      )}

      <input type="text" required placeholder="Quantity (e.g. 50 MT)" value={form.quantity}
        onChange={(e) => setForm({ ...form, quantity: e.target.value })} className={inputCls} />
      <input type="text" placeholder={isAuthed ? "Origin / Preferred city" : "Company name"} value={form.company}
        onChange={(e) => setForm({ ...form, company: e.target.value })} className={inputCls} />
      <textarea placeholder="Notes (optional)" rows={2} value={form.description}
        onChange={(e) => setForm({ ...form, description: e.target.value })} className={inputCls} />

      <button type="submit" disabled={loading}
        className="w-full bg-[#CC1414] text-white font-bold py-3.5 rounded-xl hover:bg-[#A50E0E] disabled:opacity-70 transition-colors text-sm shadow-md flex items-center justify-center gap-2">
        {loading ? <><Loader2 size={15} className="animate-spin" /> Submitting...</> : "Request Quote →"}
      </button>
    </form>
  );
}
