"use client";

import { useRef, useState } from "react";
import { useRouter } from "next/navigation";

type Attachment = {
  id: number;
  filename: string;
  contentType: string | null;
};

type Message = {
  id: number;
  direction: "INBOUND" | "OUTBOUND";
  subject: string;
  bodyText: string;
  fromAddress: string;
  toAddress: string;
  sentAt: string;
  attachments: Attachment[];
};

type ContactData = {
  id: number;
  name: string | null;
  company: string | null;
  email: string;
  phone: string | null;
  tags: string[] | null;
  dealStage: string;
  notes: string | null;
  source: string | null;
  messages: Message[];
};

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

export default function ContactDetail({ contact }: { contact: ContactData }) {
  const router = useRouter();

  const [name, setName] = useState(contact.name || "");
  const [company, setCompany] = useState(contact.company || "");
  const [phone, setPhone] = useState(contact.phone || "");
  const [tags, setTags] = useState<string[]>(contact.tags || []);
  const [dealStage, setDealStage] = useState(contact.dealStage);
  const [notes, setNotes] = useState(contact.notes || "");
  const [savingProfile, setSavingProfile] = useState(false);

  const [replySubject, setReplySubject] = useState(
    contact.messages.length > 0 ? `Re: ${contact.messages[contact.messages.length - 1].subject}` : ""
  );
  const [replyBody, setReplyBody] = useState("");
  const [file, setFile] = useState<File | null>(null);
  const fileRef = useRef<HTMLInputElement>(null);
  const [sending, setSending] = useState(false);
  const [sendError, setSendError] = useState<string | null>(null);

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

  async function saveProfile() {
    setSavingProfile(true);
    try {
      await fetch(`/api/contacts/${contact.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json", "X-Midhub-Crm": "1" },
        body: JSON.stringify({ name, company, phone, tags, dealStage, notes }),
      });
      router.refresh();
    } finally {
      setSavingProfile(false);
    }
  }

  async function sendReply(e: React.FormEvent) {
    e.preventDefault();
    setSending(true);
    setSendError(null);
    const formData = new FormData();
    formData.set("subject", replySubject);
    formData.set("body", replyBody);
    if (file) formData.set("attachment", file);

    try {
      const res = await fetch(`/api/contacts/${contact.id}/messages`, {
        method: "POST",
        headers: { "X-Midhub-Crm": "1" },
        body: formData,
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Send failed");
      setReplyBody("");
      setFile(null);
      if (fileRef.current) fileRef.current.value = "";
      router.refresh();
    } catch (err) {
      setSendError(err instanceof Error ? err.message : "Send failed");
    } finally {
      setSending(false);
    }
  }

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mt-4">
      {/* Profile panel */}
      <div className="lg:col-span-1">
        <div className="border border-black/10 rounded-lg bg-white p-5">
          <h2 className="font-heading font-600 text-lg mb-4">{contact.email}</h2>

          <label className="block text-xs font-medium text-slate mb-1">Name</label>
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            className="w-full border border-black/15 rounded-md px-3 py-1.5 text-sm mb-3 focus:outline-none focus:ring-2 focus:ring-hub-orange"
          />

          <label className="block text-xs font-medium text-slate mb-1">Company</label>
          <input
            value={company}
            onChange={(e) => setCompany(e.target.value)}
            className="w-full border border-black/15 rounded-md px-3 py-1.5 text-sm mb-3 focus:outline-none focus:ring-2 focus:ring-hub-orange"
          />

          <label className="block text-xs font-medium text-slate mb-1">Phone</label>
          <input
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
            className="w-full border border-black/15 rounded-md px-3 py-1.5 text-sm mb-3 focus:outline-none focus:ring-2 focus:ring-hub-orange"
          />

          <label className="block text-xs font-medium text-slate mb-1">Tags</label>
          <div className="flex gap-2 mb-3 flex-wrap">
            {TAG_OPTIONS.map((tag) => (
              <button
                type="button"
                key={tag}
                onClick={() => toggleTag(tag)}
                className={`px-2.5 py-1 rounded-full text-xs border ${
                  tags.includes(tag)
                    ? "bg-hub-orange text-white border-hub-orange"
                    : "border-black/15 text-slate hover:border-black/30"
                }`}
              >
                {tag}
              </button>
            ))}
          </div>

          <label className="block text-xs font-medium text-slate mb-1">Deal stage</label>
          <select
            value={dealStage}
            onChange={(e) => setDealStage(e.target.value)}
            className="w-full border border-black/15 rounded-md px-3 py-1.5 text-sm mb-3 focus:outline-none focus:ring-2 focus:ring-hub-orange"
          >
            {STAGE_OPTIONS.map((s) => (
              <option key={s} value={s}>
                {s}
              </option>
            ))}
          </select>

          <label className="block text-xs font-medium text-slate mb-1">Notes</label>
          <textarea
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            rows={4}
            className="w-full border border-black/15 rounded-md px-3 py-1.5 text-sm mb-3 focus:outline-none focus:ring-2 focus:ring-hub-orange"
          />

          {contact.source && <p className="text-xs text-slate mb-3">Source: {contact.source}</p>}

          <button
            onClick={saveProfile}
            disabled={savingProfile}
            className="w-full bg-hub-orange text-white py-1.5 rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50"
          >
            {savingProfile ? "Saving..." : "Save changes"}
          </button>
        </div>
      </div>

      {/* Thread + reply panel */}
      <div className="lg:col-span-2 space-y-4">
        <div className="space-y-3">
          {contact.messages.length === 0 && (
            <div className="border border-dashed border-black/15 rounded-lg p-8 text-center text-slate text-sm">
              No messages yet.
            </div>
          )}
          {contact.messages.map((m) => (
            <div
              key={m.id}
              className={`border rounded-lg p-4 ${
                m.direction === "OUTBOUND"
                  ? "bg-hub-orange/5 border-hub-orange/20 ml-6"
                  : "bg-white border-black/10 mr-6"
              }`}
            >
              <div className="flex items-center justify-between mb-2">
                <span className="text-xs font-medium text-slate">
                  {m.direction === "OUTBOUND" ? "Sent" : "Received"} ·{" "}
                  {new Date(m.sentAt).toLocaleString()}
                </span>
              </div>
              <div className="text-sm font-medium mb-1">{m.subject}</div>
              <p className="text-sm text-slate whitespace-pre-line">{m.bodyText}</p>
              {m.attachments.length > 0 && (
                <div className="flex gap-2 flex-wrap mt-3">
                  {m.attachments.map((a) => (
                    <a
                      key={a.id}
                      href={`/api/attachments/${a.id}`}
                      target="_blank"
                      rel="noreferrer"
                      className="text-xs bg-black/[.05] px-2 py-1 rounded hover:bg-black/[.08]"
                    >
                      📎 {a.filename}
                    </a>
                  ))}
                </div>
              )}
            </div>
          ))}
        </div>

        <form onSubmit={sendReply} className="border border-black/10 rounded-lg bg-white p-4 space-y-3">
          <h3 className="font-medium text-sm">Reply</h3>
          <input
            required
            value={replySubject}
            onChange={(e) => setReplySubject(e.target.value)}
            placeholder="Subject"
            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"
          />
          <textarea
            required
            value={replyBody}
            onChange={(e) => setReplyBody(e.target.value)}
            rows={5}
            placeholder="Write your reply..."
            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"
          />
          <input
            ref={fileRef}
            type="file"
            onChange={(e) => setFile(e.target.files?.[0] || null)}
            className="w-full text-sm file:mr-3 file:px-3 file:py-1.5 file:rounded-md file:border-0 file:bg-black/[.05] file:text-sm file:font-medium hover:file:bg-black/[.08]"
          />
          {sendError && <p className="text-red-600 text-sm">{sendError}</p>}
          <button
            type="submit"
            disabled={sending}
            className="bg-hub-green text-white px-4 py-2 rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50"
          >
            {sending ? "Sending..." : "Send reply"}
          </button>
        </form>
      </div>
    </div>
  );
}
