import type { Metadata } from "next";
import { CreatorIntro } from "@/components/site/CreatorIntro";
import { CreatorPhotoCircle } from "@/components/site/CreatorPhotoCircle";
import { submitReviewAction } from "@/lib/actions";
import { getAboutImages } from "@/lib/about-images";
import { prisma } from "@/lib/prisma";
import { siteUrl } from "@/lib/utils";

function seoKeywords(value?: string | null) {
  return value?.split(",").map((keyword) => keyword.trim()).filter(Boolean);
}

export async function generateMetadata(): Promise<Metadata> {
  const page = await prisma.pageContent.findUnique({ where: { key: "ABOUT" } }).catch(() => null);
  const { brandImage } = await getAboutImages();

  return {
    title: page?.seoTitle ?? page?.title ?? "About",
    description: page?.seoDescription ?? page?.subtitle ?? "Learn about Just Chill Nepal and the idea behind the platform.",
    keywords: seoKeywords(page?.seoKeywords),
    alternates: { canonical: siteUrl("/about") },
    openGraph: {
      title: page?.seoTitle ?? page?.title ?? "About Just Chill Nepal",
      description: page?.seoDescription ?? page?.subtitle ?? "Learn about Just Chill Nepal and the idea behind the platform.",
      images: brandImage ? [{ url: brandImage, alt: page?.title ?? "Just Chill Nepal" }] : undefined,
      url: siteUrl("/about"),
      type: "website"
    },
    twitter: {
      card: brandImage ? "summary_large_image" : "summary",
      title: page?.seoTitle ?? page?.title ?? "About Just Chill Nepal",
      description: page?.seoDescription ?? page?.subtitle ?? "Learn about Just Chill Nepal and the idea behind the platform.",
      images: brandImage ? [brandImage] : undefined
    }
  };
}

const defaultSocialUrl = "https://justchillnepal.com";
const socialLinks = [
  { key: "facebook", label: "Facebook" },
  { key: "instagram", label: "Instagram" },
  { key: "youtube", label: "YouTube" },
  { key: "tiktok", label: "TikTok" },
  { key: "linkedin", label: "LinkedIn" },
  { key: "xUrl", label: "X" },
  { key: "portfolio", label: "Portfolio" },
  { key: "whatsapp", label: "WhatsApp" }
] as const;

const defaultCreatorSkills = [
  "Web Developer",
  "Photographer",
  "Content Creator",
  "Traveler",
  "Freelancer",
  "IT Support Engineer",
  "UI/UX Designer"
];

type AboutPageProps = {
  searchParams: Promise<{ review?: string }>;
};

export default async function AboutPage({ searchParams }: AboutPageProps) {
  const params = await searchParams;
  const [page, contact, images] = await Promise.all([
    prisma.pageContent.findUnique({ where: { key: "ABOUT" } }),
    prisma.contactSetting.findUnique({ where: { key: "contact" } }),
    getAboutImages()
  ]);

  const creatorName = contact?.fullName || "Dipak Basnet";
  const creatorSkills =
    contact?.creatorSkills
      ?.split(/\r?\n/)
      .map((skill) => skill.trim())
      .filter(Boolean)
      .slice(0, 12) ?? defaultCreatorSkills;

  return (
    <main className="container" style={{ padding: "4rem 1.25rem" }}>
      <CreatorIntro about={page} brandImage={images.brandImage} />

      <section className="creator-profile-section">
        <div className="creator-profile-card">
          <span className="pill">Creator Details</span>
          <h2 className="section-title">{creatorName}</h2>
          <p className="muted">The creator behind Just Chill Nepal.</p>

          <div className="creator-info-list">
            <div>
              <strong>Name</strong>
              <span>{creatorName}</span>
            </div>
            <div>
              <strong>Phone</strong>
              <span>{contact?.phone || "Update from admin panel"}</span>
            </div>
            <div>
              <strong>Address</strong>
              <span>{contact?.address || "Update from admin panel"}</span>
            </div>
            <div>
              <strong>Experience</strong>
              <span>
                {contact?.creatorExperience ||
                  "Content creator, traveler, IT support engineer, and digital media enthusiast."}
              </span>
            </div>
          </div>

          <div className="creator-social-links">
            {socialLinks.map((social) => (
              <a href={contact?.[social.key] || defaultSocialUrl} key={social.key} rel="noreferrer" target="_blank">
                {social.label}
              </a>
            ))}
          </div>
        </div>

        <CreatorPhotoCircle
          alt={creatorName}
          className="creator-profile-photo"
          imageUrl={images.creatorImage}
          placeholder="Upload creator photo from Admin → Creator Intro"
          skills={creatorSkills}
        />
      </section>

      <section className="transparent-section" style={{ marginTop: "3rem" }}>
        <div className="section-head">
          <div>
            <span className="pill">Viewer Review</span>
            <h2 className="section-title">Share Your Feedback</h2>
            <p className="muted">Your review will appear on the website after admin approval.</p>
          </div>
        </div>

        <form action={submitReviewAction} className="contact-form-pro">
          {params.review === "sent" ? (
            <div className="contact-success-message" role="status">
              <strong>Thank you for your review!</strong>
              <span>Your feedback has been submitted and will be visible after admin approval.</span>
            </div>
          ) : null}
          {params.review === "error" ? (
            <p className="admin-error-message">Please enter your name, rating, and a message of at least 5 characters.</p>
          ) : null}
          <div className="contact-form-row">
            <label className="field">
              Full Name
              <input name="name" placeholder="Enter your name" required />
            </label>
            <label className="field">
              Location
              <input name="location" placeholder="Pokhara, Nepal" />
            </label>
          </div>
          <label className="field">
            Rating
            <input defaultValue="5" max="5" min="1" name="rating" type="number" />
          </label>
          <label className="field">
            Review Message
            <textarea name="message" placeholder="Write your feedback..." required />
          </label>
          <button className="btn contact-submit" type="submit">
            Submit Review
          </button>
        </form>
      </section>
    </main>
  );
}
