"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";

const TAG_OPTIONS = ["lead", "customer", "vendor"];
const STAGE_OPTIONS = ["NEW", "CONTACTED", "QUALIFIED", "PROPOSAL", "WON", "LOST"];

export default function NewContactPage() {
  const router = useRouter();
  const [form, setForm] = useState({
    name: "",
    company: "",
    email: "",
    phone: "",
    dealStage: "NEW",
    notes: "",
    source: "Manual add",
  });
  const [tags, setTags] = useState<string[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  function set<K extends keyof typeof form>(key: K, value: string) {
    setForm((prev) => ({ ...prev, [key]: value }));
  }

  function toggleTag(tag: string) {
    setTags((prev) => (prev.includes(tag) ? prev.filter((t) => t !== tag) : [...prev, tag]));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setSubmitting(true);
    try {
      const res = await fetch("/api/contacts", {
        method: "POST",
        headers: { "Content-Type": "application/json", "X-Midhub-Crm": "1" },
        body: JSON.stringify({ ...form, tags }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Something went wrong");
      router.push(`/contacts/${data.id}`);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Something went wrong");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="max-w-lg">
      <Link href="/contacts" className="text-sm text-slate hover:underline">
        ← Back to contacts
      </Link>
      <h1 className="font-heading font-600 text-2xl mt-2 mb-6">Add a contact</h1>

      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="block text-sm font-medium mb-1">Name</label>
          <input
            value={form.name}
            onChange={(e) => set("name", e.target.value)}
            className="w-full border border-black/15 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-hub-orange"
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Company</label>
          <input
            value={form.company}
            onChange={(e) => set("company", e.target.value)}
            className="w-full border border-black/15 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-hub-orange"
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Email</label>
          <input
            required
            type="email"
            value={form.email}
            onChange={(e) => set("email", e.target.value)}
            className="w-full border border-black/15 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-hub-orange"
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Phone</label>
          <input
            value={form.phone}
            onChange={(e) => set("phone", e.target.value)}
            className="w-full border border-black/15 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-hub-orange"
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Tags</label>
          <div className="flex gap-2">
            {TAG_OPTIONS.map((tag) => (
              <button
                type="button"
                key={tag}
                onClick={() => toggleTag(tag)}
                className={`px-3 py-1 rounded-full text-sm border ${
                  tags.includes(tag)
                    ? "bg-hub-orange text-white border-hub-orange"
                    : "border-black/15 text-slate hover:border-black/30"
                }`}
              >
                {tag}
              </button>
            ))}
          </div>
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Deal stage</label>
          <select
            value={form.dealStage}
            onChange={(e) => set("dealStage", e.target.value)}
            className="w-full border border-black/15 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-hub-orange"
          >
            {STAGE_OPTIONS.map((s) => (
              <option key={s} value={s}>
                {s}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Source</label>
          <input
            value={form.source}
            onChange={(e) => set("source", e.target.value)}
            className="w-full border border-black/15 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-hub-orange"
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Notes</label>
          <textarea
            value={form.notes}
            onChange={(e) => set("notes", e.target.value)}
            rows={4}
            className="w-full border border-black/15 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-hub-orange"
          />
        </div>

        {error && <p className="text-red-600 text-sm">{error}</p>}

        <button
          type="submit"
          disabled={submitting}
          className="bg-hub-orange text-white px-4 py-2 rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50"
        >
          {submitting ? "Adding..." : "Add contact"}
        </button>
      </form>
    </div>
  );
}
