import { z } from "zod";

import { linkSchema } from "@/features/settings/schemas";
import { SLUG_MAX_LENGTH, SLUG_PATTERN } from "@/lib/slug";

export const TITLE_MAX = 200;
export const EXCERPT_MAX = 500;
export const EXCERPT_RECOMMENDED = 160;
export const MAX_FAQS = 50;
export const MAX_TAGS = 20;
/** Matches the three-card related rail on the website. */
export const MAX_RELATED = 3;
/** Article HTML, not counting images (stored as URLs). */
export const CONTENT_MAX = 500_000;

/** Save buttons in the editor. Autosave never changes status or goes live. */
export const saveIntents = [
  "autosave",
  "draft",
  "publish",
  "schedule",
  "update",
  "unpublish",
] as const;
export type SaveIntent = (typeof saveIntents)[number];

const text = (max: number) => z.string().max(max, `Keep this under ${max} characters.`);

/** Optional image URL: a root-relative upload path or an http(s) URL. */
const imageUrl = z
  .string()
  .trim()
  .max(1000)
  .refine(
    (value) => value === "" || /^\/uploads\//.test(value) || /^https?:\/\/\S+$/i.test(value),
    "Choose an image from the media library.",
  );

/**
 * How the CTA's link is drawn: Apple's "Download on the App Store" badge (what
 * the website's sidebar card uses) or a plain text button.
 */
export const ctaButtonStyles = ["APP_STORE", "BUTTON"] as const;
export type CtaButtonStyle = (typeof ctaButtonStyles)[number];

/** The Wi-Fi Calling & Texting iOS app, as linked from the website's CTA card. */
export const APP_STORE_URL = "https://apps.apple.com/app/id6781677176";
/** Screen-reader label for the badge; the public API needs button text to show the CTA. */
export const APP_STORE_BADGE_LABEL = "Download on the App Store";

/** True for apps.apple.com, itunes.apple.com and apple.co links. */
export const isAppStoreUrl = (url: string) =>
  /^https?:\/\/(?:apps\.apple\.com|itunes\.apple\.com|apple\.co)(?:\/|$)/i.test(url.trim());

/** The style for a CTA that has none stored (until Laravel saves `cta_button_style`). */
export const inferCtaButtonStyle = (url: string): CtaButtonStyle =>
  isAppStoreUrl(url) ? "APP_STORE" : "BUTTON";

export const faqSchema = z.object({
  /** Database ID, or a client-generated one for new items. */
  id: z.string().max(64),
  question: text(300),
  answer: text(5000),
});

/**
 * Everything the editor edits. Shared by the client form state, autosave
 * snapshots, revisions and the save action.
 */
export const blogFormSchema = z.object({
  title: text(TITLE_MAX),
  slug: z
    .string()
    .max(SLUG_MAX_LENGTH, `Slugs can be up to ${SLUG_MAX_LENGTH} characters.`)
    .refine(
      (value) => value === "" || SLUG_PATTERN.test(value),
      "Use lowercase letters, numbers and single hyphens.",
    ),
  excerpt: text(EXCERPT_MAX),
  content: z.string().max(CONTENT_MAX, "The article is too long to save."),

  featuredImage: imageUrl,
  featuredImageAlt: text(300),
  featuredImageTitle: text(200),

  categoryId: z.string().max(64).nullable(),
  authorId: z.string().max(64).nullable(),
  tags: z.array(z.string().trim().min(1).max(40)).max(MAX_TAGS, `Use at most ${MAX_TAGS} tags.`),
  /** ISO timestamp chosen in Publish date/time, or null for "immediately". */
  publishedAt: z.iso.datetime({ offset: true }).nullable(),

  seoTitle: text(120),
  metaDescription: text(320),
  canonicalUrl: z
    .string()
    .trim()
    .max(500)
    .refine((value) => value === "" || /^https?:\/\/\S+$/i.test(value), "Use a full https:// URL."),
  focusKeyword: text(100),
  ogTitle: text(120),
  ogDescription: text(320),
  ogImage: imageUrl,
  robotsIndex: z.boolean(),
  robotsFollow: z.boolean(),

  faqs: z.array(faqSchema).max(MAX_FAQS, `Use at most ${MAX_FAQS} questions.`),
  faqSchemaEnabled: z.boolean(),

  ctaEnabled: z.boolean(),
  ctaTitle: text(120),
  ctaDescription: text(300),
  ctaButtonText: text(40),
  ctaButtonUrl: linkSchema,
  ctaButtonStyle: z.enum(ctaButtonStyles),
  ctaImage: imageUrl,

  relatedMode: z.enum(["AUTOMATIC", "MANUAL"]),
  relatedBlogIds: z
    .array(z.string().max(64))
    .max(MAX_RELATED, `Pick at most ${MAX_RELATED} related articles.`),
});

export type BlogFormValues = z.infer<typeof blogFormSchema>;

/** Metadata the editor tracks alongside the form, returned by every save. */
export type BlogEditorMeta = {
  id: string;
  status: "DRAFT" | "SCHEDULED" | "PUBLISHED";
  slug: string;
  version: number;
  publishedAt: string | null;
  scheduledAt: string | null;
  updatedAt: string;
  /** Set when unsaved changes to a live article are held in autosave. */
  autosavedAt: string | null;
  /** The slug readers currently see, for live articles. */
  liveSlug: string | null;
  revisionCount: number;
};

export type SaveBlogResult = { blog: BlogEditorMeta; values: BlogFormValues };

/** Extra rules that apply only when an article goes live. */
export function publishIssues(values: BlogFormValues) {
  const issues: Record<string, string> = {};
  if (!values.title.trim()) issues.title = "Add a title before publishing.";
  if (!values.slug) issues.slug = "Add a URL slug before publishing.";
  if (!values.content.replace(/<[^>]*>/g, "").trim() && !/<img\b/i.test(values.content)) {
    issues.content = "Write some content before publishing.";
  }
  values.faqs.forEach((faq, index) => {
    if (!faq.question.trim()) issues[`faqs.${index}.question`] = "Add a question or remove this FAQ.";
    if (!faq.answer.trim()) issues[`faqs.${index}.answer`] = "Add an answer or remove this FAQ.";
  });
  if (values.ctaEnabled) {
    if (!values.ctaTitle.trim()) issues.ctaTitle = "Add a CTA title, or turn the CTA off.";
    if (!values.ctaButtonText.trim()) {
      issues.ctaButtonText =
        values.ctaButtonStyle === "APP_STORE"
          ? "Add a badge label, or turn the CTA off."
          : "Add button text, or turn the CTA off.";
    }
    if (!values.ctaButtonUrl.trim()) {
      issues.ctaButtonUrl = "Add a button URL, or turn the CTA off.";
    } else if (values.ctaButtonStyle === "APP_STORE" && !isAppStoreUrl(values.ctaButtonUrl)) {
      issues.ctaButtonUrl = "The App Store badge needs an apps.apple.com or apple.co link.";
    }
  }
  return issues;
}
