import { AdminFileForm } from "@/admin/components/AdminFileForm";
import { AdminRowActions } from "@/admin/components/AdminRowActions";
import {
  approveReviewAction,
  deleteReviewAction,
  deleteSlideAction,
  saveAboutBrandPhotoAction,
  saveAboutCreatorPhotoAction,
  saveFaviconBrandingAction,
  saveLogoBrandingAction,
  saveNeuralThemeAction,
  saveReviewAction,
  saveSlideAction
} from "@/lib/actions";
import { requirePermission } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";

type AdminHomeSectionPageProps = {
  params: Promise<{ section: string }>;
  searchParams: Promise<{ error?: string; saved?: string }>;
};

const errorMessages: Record<string, string> = {
  "file-size": "Each file must be 20 MB or smaller.",
  upload: "Upload failed. Check file size (max 20 MB per file) and ensure MySQL is running.",
  logo: "Please choose a logo file before saving.",
  favicon: "Please choose a favicon file before saving.",
  branding: "Please choose a logo or favicon image before saving.",
  "brand-photo": "Please choose a Just Chill Nepal brand photo before saving.",
  "creator-photo": "Please choose a creator photo before saving.",
  "intro-photo": "Please choose a photo before saving.",
  "neural-theme": "Please choose valid hex colors for the neural background.",
  "slide-image": "Please upload an image or enter an image URL for the slider.",
  "slide-required": "Please fill slider title and subtitle before saving.",
  "slide-size": "Slider uploaded image must be at least 1080 x 1920 pixels."
};

const sectionCopy: Record<string, { eyebrow: string; title: string; description: string }> = {
  "background-theme": {
    description: "Change the futuristic 3D neural network background colors shown on the public website.",
    eyebrow: "Background Control",
    title: "Background Theme"
  },
  "branding": {
    description: "Upload the public website logo and browser favicon.",
    eyebrow: "Brand Control",
    title: "Branding"
  },
  "creator-intro": {
    description: "Upload separate photos for Just Chill Nepal (brand) and Dipak Basnet (creator).",
    eyebrow: "About photos",
    title: "Brand & creator photos"
  },
  "image-slider": {
    description: "Add and manage gallery slider images, titles, subtitles, and CTA links.",
    eyebrow: "Slider Control",
    title: "Image Slider"
  },
  "viewer-reviews": {
    description: "Add and manage homepage viewer feedback cards.",
    eyebrow: "Review Control",
    title: "Viewer Reviews"
  }
};

export default async function AdminHomeSectionPage({ params, searchParams }: AdminHomeSectionPageProps) {
  const session = await requirePermission("home");
  const [{ section }, query] = await Promise.all([params, searchParams]);
  const copy = sectionCopy[section];

  if (!copy) {
    notFound();
  }

  const [slides, reviews, about, setting] = await Promise.all([
    prisma.homeSlide.findMany({ orderBy: [{ sortOrder: "asc" }, { createdAt: "desc" }] }),
    prisma.review.findMany({ orderBy: { createdAt: "desc" } }),
    prisma.pageContent.findUnique({ where: { key: "ABOUT" } }),
    prisma.siteSetting.findUnique({ where: { key: "site" } })
  ]);

  return (
      <>

      <div className="section-head">
        <div>
          <span className="pill">{copy.eyebrow}</span>
          <h1 className="admin-title">{copy.title}</h1>
          <p className="muted">{copy.description}</p>
        </div>
        <Link className="btn btn-secondary" href="/admin/home">Back to Home Sections</Link>
      </div>
      {query.error ? (
        <p className="admin-error-message">{errorMessages[query.error] ?? "Something went wrong. Please check the form and try again."}</p>
      ) : null}

      {section === "branding" ? (
        <div className="main-layout branding-upload-layout">
          {query.saved === "1" ? (
            <p
              className="admin-success-message"
              style={{ background: "var(--admin-blue-soft)", color: "var(--admin-blue)", gridColumn: "1 / -1" }}
            >
              Saved successfully.
            </p>
          ) : null}
          <AdminFileForm action={saveLogoBrandingAction} className="info-panel">
            <div className="panel-header">Website Logo</div>
            <p className="muted" style={{ lineHeight: 1.7 }}>
              Shown in the site header and footer. Any format, up to 20 MB. Save logo and favicon separately.
            </p>
            <label className="field">
              Logo file
              <input name="logoFile" type="file" />
            </label>
            <button className="btn" type="submit">
              Save Logo
            </button>
          </AdminFileForm>

          <AdminFileForm action={saveFaviconBrandingAction} className="info-panel">
            <div className="panel-header">Favicon</div>
            <p className="muted" style={{ lineHeight: 1.7 }}>
              Browser tab icon. Any format, up to 20 MB.
            </p>
            <label className="field">
              Favicon file
              <input name="faviconFile" type="file" />
            </label>
            <button className="btn" type="submit">
              Save Favicon
            </button>
          </AdminFileForm>

          <div className="map-panel branding-preview-panel">
            <div className="panel-header">Current Branding</div>
            <div className="grid-cards">
              <div className="card">
                <span className="pill">Logo</span>
                {setting?.logoUrl ? (
                  <Image alt="Current logo" height={160} src={setting.logoUrl} style={{ borderRadius: 16, marginTop: 12, objectFit: "cover", width: "100%" }} unoptimized width={320} />
                ) : (
                  <p className="muted" style={{ marginTop: 12 }}>Default J logo is active.</p>
                )}
              </div>
              <div className="card">
                <span className="pill">Favicon</span>
                {setting?.faviconUrl ? (
                  <Image alt="Current favicon" height={96} src={setting.faviconUrl} style={{ borderRadius: 16, marginTop: 12, objectFit: "cover" }} unoptimized width={96} />
                ) : (
                  <p className="muted" style={{ marginTop: 12 }}>Default favicon is active.</p>
                )}
              </div>
            </div>
          </div>
        </div>
      ) : null}

      {section === "background-theme" ? (
        <form action={saveNeuralThemeAction} className="glass-panel form-grid">
          <div className="panel-header">Neural Background Colors</div>
          <p className="muted" style={{ gridColumn: "1 / -1", lineHeight: 1.7 }}>
            Change the futuristic 3D neural network background colors shown on the public website.
          </p>
          <label className="field">
            Primary Color
            <input defaultValue={setting?.neuralColorA ?? "#00ffff"} name="neuralColorA" type="color" />
          </label>
          <label className="field">
            Secondary Color
            <input defaultValue={setting?.neuralColorB ?? "#0088ff"} name="neuralColorB" type="color" />
          </label>
          <label className="field">
            Highlight Color
            <input defaultValue={setting?.neuralColorC ?? "#ffd700"} name="neuralColorC" type="color" />
          </label>
          <button className="btn" type="submit">Save Background Colors</button>
        </form>
      ) : null}

      {section === "creator-intro" ? (
        <div className="dashboard-grid">
          {query.saved === "brand" ? (
            <p className="admin-success-message" style={{ gridColumn: "1 / -1" }}>
              Just Chill Nepal brand photo saved.
            </p>
          ) : null}
          {query.saved === "creator" ? (
            <p className="admin-success-message" style={{ gridColumn: "1 / -1" }}>
              Creator photo saved.
            </p>
          ) : null}

          <AdminFileForm action={saveAboutBrandPhotoAction} className="glass-panel form-grid span-6">
            <div className="panel-header">Just Chill Nepal photo</div>
            <p className="muted" style={{ gridColumn: "1 / -1", lineHeight: 1.7 }}>
              Shown at the top of the About page and home intro. Hover shows brand topics around the circle.
            </p>
            <label className="field">
              Brand photo
              <input accept="image/*" name="brandPhoto" required type="file" />
            </label>
            <button className="btn" type="submit">
              Save brand photo
            </button>
          </AdminFileForm>

          <AdminFileForm action={saveAboutCreatorPhotoAction} className="glass-panel form-grid span-6">
            <div className="panel-header">Dipak Basnet (creator) photo</div>
            <p className="muted" style={{ gridColumn: "1 / -1", lineHeight: 1.7 }}>
              Shown in the creator section on About. Skills from Admin Contact appear on hover around the circle.
            </p>
            <label className="field">
              Creator photo
              <input accept="image/*" name="creatorPhoto" required type="file" />
            </label>
            <button className="btn" type="submit">
              Save creator photo
            </button>
          </AdminFileForm>

          <div className="glass-panel span-6">
            <div className="panel-header">Current brand photo</div>
            {setting?.aboutBrandImageUrl ? (
              <Image alt="Just Chill Nepal" height={280} src={setting.aboutBrandImageUrl} style={{ borderRadius: "50%", marginTop: 12, objectFit: "cover", width: "100%", maxWidth: 280 }} unoptimized width={280} />
            ) : (
              <p className="muted">No brand photo uploaded yet.</p>
            )}
          </div>

          <div className="glass-panel span-6">
            <div className="panel-header">Current creator photo</div>
            {setting?.aboutCreatorImageUrl ? (
              <Image alt="Creator" height={280} src={setting.aboutCreatorImageUrl} style={{ borderRadius: "50%", marginTop: 12, objectFit: "cover", width: "100%", maxWidth: 280 }} unoptimized width={280} />
            ) : (
              <p className="muted">No creator photo uploaded yet.</p>
            )}
          </div>
        </div>
      ) : null}

      {section === "image-slider" ? (
        <div className="main-layout">
          <form action={saveSlideAction} className="info-panel">
            <div className="panel-header">Add Slider Image</div>
            <p className="muted" style={{ lineHeight: 1.7 }}>
              Uploaded slider image must be at least 1080 x 1920 pixels for best quality.
            </p>
            <label className="field">
              Image Upload
              <input name="imageFile" type="file" />
            </label>
            <label className="field">
              Image URL (optional)
              <input name="imageUrl" placeholder="/uploads/banner.jpg or https://..." />
            </label>
            <label className="field">
              Title
              <input name="title" required />
            </label>
            <label className="field">
              Subtitle
              <textarea name="subtitle" required />
            </label>
            <label className="field">
              CTA Label
              <input name="ctaLabel" placeholder="Watch Videos" />
            </label>
            <label className="field">
              CTA Link
              <input name="ctaHref" placeholder="/videos" />
            </label>
            <label className="field">
              Sort Order
              <input defaultValue="0" name="sortOrder" type="number" />
            </label>
            <label className="checklist-item active">
              <span className="check-box" />
              <input defaultChecked name="active" style={{ display: "none" }} type="checkbox" />
              Active
            </label>
            <button className="btn" type="submit">Save Slide</button>
          </form>

          <div className="map-panel">
            <div className="panel-header">Current Slides</div>
            <div className="grid-cards">
              {slides.map((slide) => (
                <div className="card" key={slide.id}>
                  <Image alt={slide.title} height={130} src={slide.imageUrl} style={{ borderRadius: 8, objectFit: "cover", width: "100%" }} unoptimized width={320} />
                  <h3 style={{ color: "var(--jarvis-blue)", margin: "12px 0" }}>{slide.title}</h3>
                  <p className="muted">{slide.subtitle}</p>
                  <div style={{ marginTop: 12 }}>
                    <AdminRowActions
                      deleteAction={deleteSlideAction}
                      deleteConfirm={`Delete slide "${slide.title}"?`}
                      deleteId={slide.id}
                    />
                  </div>
                </div>
              ))}
              {slides.length === 0 ? <p className="muted">No slides yet.</p> : null}
            </div>
          </div>
        </div>
      ) : null}

      {section === "viewer-reviews" ? (
        <div className="main-layout">
          <form action={saveReviewAction} className="info-panel">
            <div className="panel-header">Add Review</div>
            <label className="field">
              Name
              <input name="name" required />
            </label>
            <label className="field">
              Location
              <input name="location" placeholder="Pokhara, Nepal" />
            </label>
            <label className="field">
              Rating
              <input defaultValue="5" max="5" min="1" name="rating" type="number" />
            </label>
            <label className="field">
              Message
              <textarea name="message" required />
            </label>
            <label className="checklist-item active">
              <span className="check-box" />
              <input defaultChecked name="active" style={{ display: "none" }} type="checkbox" />
              Active
            </label>
            <button className="btn" type="submit">Save Review</button>
          </form>

          <div className="map-panel">
            <div className="panel-header">Current Reviews</div>
            <div className="grid-cards">
              {reviews.map((review) => (
                <div className="card" key={review.id}>
                  <span className="pill">{review.rating}/5 · {review.approvalStatus}</span>
                  <h3 style={{ color: "var(--jarvis-blue)", margin: "12px 0" }}>{review.name}</h3>
                  <p className="muted">{review.location}</p>
                  <p style={{ lineHeight: 1.7 }}>{review.message}</p>
                  <div className="admin-actions" style={{ marginTop: 12 }}>
                    {review.approvalStatus !== "APPROVED" ? (
                      <form action={approveReviewAction}>
                        <input name="id" type="hidden" value={review.id} />
                        <input name="approved" type="hidden" value="true" />
                        <button className="btn btn-secondary" type="submit">Approve</button>
                      </form>
                    ) : null}
                    {review.approvalStatus !== "REJECTED" ? (
                      <form action={approveReviewAction}>
                        <input name="id" type="hidden" value={review.id} />
                        <input name="approved" type="hidden" value="false" />
                        <button className="btn btn-secondary" type="submit">Reject</button>
                      </form>
                    ) : null}
                    <AdminRowActions
                      deleteAction={deleteReviewAction}
                      deleteConfirm={`Delete review from ${review.name}?`}
                      deleteId={review.id}
                    />
                  </div>
                </div>
              ))}
              {reviews.length === 0 ? <p className="muted">No reviews yet.</p> : null}
            </div>
          </div>
        </div>
      ) : null}
      </>
    );
}
