"use client";

import { useEffect, useState, type CSSProperties, type FormEvent } from "react";

type DesignPayload = {
  partnerOne: string;
  partnerTwo: string;
  weddingDate: string;
  heading: string;
  message: string;
  footer: string;
  font: "editorial" | "modern" | "romantic";
  fontSize: number;
  alignment: "left" | "center";
  palette: "ivory" | "blush" | "sage" | "stone" | "white";
};

type ShareComment = { id: string; name: string; message: string; createdAt: string };
type SharedDesign = { design: DesignPayload; createdAt: string; comments: ShareComment[] };

const palettes = {
  ivory: { card: "#f4efe5", ink: "#332a21", accent: "#a78349" },
  blush: { card: "#f2e7e4", ink: "#4c302d", accent: "#a7786d" },
  sage: { card: "#e7ebe2", ink: "#28372d", accent: "#7b8b70" },
  stone: { card: "#e8e5df", ink: "#2d2c2a", accent: "#898178" },
  white: { card: "#ffffff", ink: "#27231f", accent: "#aa8952" },
};

const fonts = {
  editorial: "Georgia, 'Times New Roman', serif",
  modern: "Arial, Helvetica, sans-serif",
  romantic: "'Palatino Linotype', Palatino, serif",
};

function formatWeddingDate(date: string) {
  if (!date) return "YOUR WEDDING DATE";
  return new Intl.DateTimeFormat("en-ZA", { day: "2-digit", month: "long", year: "numeric" })
    .format(new Date(`${date}T12:00:00`))
    .toUpperCase();
}

function formatCommentDate(date: string) {
  return new Intl.DateTimeFormat("en-ZA", { day: "numeric", month: "short", year: "numeric" }).format(new Date(date));
}

export default function SharedDesignPage() {
  const [token, setToken] = useState("");
  const [shared, setShared] = useState<SharedDesign | null>(null);
  const [loadStatus, setLoadStatus] = useState<"loading" | "ready" | "error">("loading");
  const [loadMessage, setLoadMessage] = useState("");
  const [shareUrl, setShareUrl] = useState("");
  const [copyMessage, setCopyMessage] = useState("");
  const [commentName, setCommentName] = useState("");
  const [commentMessage, setCommentMessage] = useState("");
  const [commentStatus, setCommentStatus] = useState<"idle" | "posting" | "error">("idle");
  const [commentFeedback, setCommentFeedback] = useState("");

  useEffect(() => {
    const currentToken = new URLSearchParams(window.location.search).get("token") || "";
    setToken(currentToken);
    setShareUrl(window.location.href);
    if (!currentToken) {
      setLoadStatus("error");
      setLoadMessage("This shared design link is incomplete.");
      return;
    }

    fetch(`/api/shares?token=${encodeURIComponent(currentToken)}`)
      .then(async (response) => {
        const result = await response.json() as { share?: SharedDesign; error?: string };
        if (!response.ok || !result.share) throw new Error(result.error || "Unable to load this shared design.");
        setShared(result.share);
        setLoadStatus("ready");
      })
      .catch((error: unknown) => {
        setLoadStatus("error");
        setLoadMessage(error instanceof Error ? error.message : "Unable to load this shared design.");
      });
  }, []);

  async function copyLink(message = "Link copied.") {
    try {
      await navigator.clipboard.writeText(shareUrl);
      setCopyMessage(message);
    } catch {
      setCopyMessage("Copy the link from your browser address bar.");
    }
  }

  async function submitComment(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setCommentStatus("posting");
    setCommentFeedback("");
    try {
      const response = await fetch("/api/shares/comments", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, name: commentName, message: commentMessage }),
      });
      const result = await response.json() as { comment?: ShareComment; error?: string };
      if (!response.ok || !result.comment) throw new Error(result.error || "Unable to post your comment.");
      setShared((current) => current ? { ...current, comments: [...current.comments, result.comment as ShareComment] } : current);
      setCommentMessage("");
      setCommentStatus("idle");
      setCommentFeedback("Your comment is now visible.");
    } catch (error) {
      setCommentStatus("error");
      setCommentFeedback(error instanceof Error ? error.message : "Unable to post your comment.");
    }
  }

  const design = shared?.design;
  const selectedPalette = design ? palettes[design.palette] : palettes.ivory;
  const cardStyle = design ? {
    "--card-bg": selectedPalette.card,
    "--card-ink": selectedPalette.ink,
    "--card-accent": selectedPalette.accent,
    "--card-scale": design.fontSize / 100,
    "--card-font": fonts[design.font],
    textAlign: design.alignment,
  } as CSSProperties : undefined;
  const coupleNames = design ? `${design.partnerOne || "Partner one"} & ${design.partnerTwo || "Partner two"}` : "";
  const showFeaturedCouple = design?.heading.trim().toUpperCase() === "THE WEDDING OF";

  return (
    <main className="shared-page">
      <header className="shared-header">
        <a className="brand" href="/" aria-label="Visit the Gem Vial website">
          <img className="brand-mark" src="/logo.svg" width="24" height="38" alt="" aria-hidden="true" />
          <span>Gem Vial</span>
        </a>
        <a href="/">Discover Gem Vial <span>↗</span></a>
      </header>

      {loadStatus === "loading" && <section className="shared-state"><img src="/logo.svg" width="34" height="54" alt="" /><p>Opening the shared design…</p></section>}
      {loadStatus === "error" && <section className="shared-state error"><img src="/logo.svg" width="34" height="54" alt="" /><h1>We couldn’t open this design.</h1><p>{loadMessage}</p><a className="button button-dark" href="/">Visit Gem Vial</a></section>}

      {loadStatus === "ready" && design && (
        <>
          <section className="shared-design-layout">
            <div className="shared-card-stage">
              <article className={`wedding-card align-${design.alignment}`} style={cardStyle} aria-label="Shared personalised Gem Vial card design">
                <div className="card-heading">{design.heading}</div>
                {showFeaturedCouple && <div className="card-couple card-couple-feature">{coupleNames}</div>}
                <div className="card-ornament"><span /><b>♡</b><span /></div>
                <div className="card-message">{design.message.split("\n").map((line, index) => <span key={`${line}-${index}`}>{line}</span>)}</div>
                <div className="card-vial-wrap" aria-hidden="true">
                  <div className="card-vial">
                    <div className="card-vial-glass"><img src="/diamond-single-28.png" width="29" height="29" alt="" /></div>
                    <div className="card-vial-cap" />
                  </div>
                </div>
                <div className="card-footer-text">{design.footer}</div>
                <div className="card-couple">{coupleNames}</div>
                <div className="card-date">{formatWeddingDate(design.weddingDate)}</div>
              </article>
            </div>

            <div className="shared-design-copy">
              <p className="eyebrow"><span /> A design shared with you</p>
              <h1>A piece of their<br /><em>forever.</em></h1>
              <p>{coupleNames} shared their personalised Gem Vial wedding favour card with you.</p>
              <div className="public-link-note"><strong>View-only public link</strong><span>This token cannot open or edit their private design.</span></div>
              <div className="shared-socials" aria-label="Share this design">
                <a href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl)}`} target="_blank" rel="noreferrer">Facebook</a>
                <button type="button" onClick={() => copyLink("Link copied—paste it into Instagram.")}>Instagram</button>
                <a href={`https://wa.me/?text=${encodeURIComponent(`A Gem Vial design shared with you: ${shareUrl}`)}`} target="_blank" rel="noreferrer">WhatsApp</a>
                <a href={`mailto:?subject=${encodeURIComponent("A Gem Vial design")}&body=${encodeURIComponent(`A Gem Vial design has been shared with you:\n\n${shareUrl}`)}`}>Email</a>
                <button type="button" onClick={() => copyLink()}>Copy link</button>
              </div>
              {copyMessage && <p className="shared-feedback" role="status">{copyMessage}</p>}
              <a className="shared-home-link" href="/">Create your own Gem Vial design <span>→</span></a>
            </div>
          </section>

          <section className="shared-comments">
            <div className="shared-comments-heading">
              <div><p className="eyebrow"><span /> Guest book</p><h2>Leave a comment.</h2></div>
              <p>Comments are public to everyone with this link.</p>
            </div>
            <div className="shared-comments-grid">
              <form onSubmit={submitComment}>
                <label><span>Your name</span><input value={commentName} onChange={(event) => setCommentName(event.target.value)} required minLength={2} maxLength={80} /></label>
                <label><span>Your comment</span><textarea value={commentMessage} onChange={(event) => setCommentMessage(event.target.value)} required minLength={2} maxLength={500} rows={5} placeholder="Share a message for the couple…" /></label>
                <button className="button button-dark" type="submit" disabled={commentStatus === "posting"}>{commentStatus === "posting" ? "Posting…" : "Post comment"}</button>
                {commentFeedback && <p className={`comment-feedback ${commentStatus}`} role="status">{commentFeedback}</p>}
              </form>
              <div className="shared-comment-list">
                {shared.comments.length ? shared.comments.map((comment) => (
                  <article key={comment.id}><div><strong>{comment.name}</strong><time dateTime={comment.createdAt}>{formatCommentDate(comment.createdAt)}</time></div><p>{comment.message}</p></article>
                )) : <div className="no-comments"><span>♡</span><p>Be the first to leave a message.</p></div>}
              </div>
            </div>
          </section>
        </>
      )}
    </main>
  );
}
