"use client";

import { ArrowRightIcon, LinkIcon, MonitorIcon, RotateCcwIcon, SmartphoneIcon, type LucideIcon } from "lucide-react";
import { useState, type ReactNode } from "react";

import { ImageField } from "@/components/media/image-field";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import {
  APP_STORE_BADGE_LABEL,
  APP_STORE_URL,
  inferCtaButtonStyle,
  isAppStoreUrl,
  type BlogFormValues,
  type CtaButtonStyle,
} from "@/features/blogs/schemas";
import { cn } from "@/lib/utils";

import { useBlogEditor } from "./editor-context";
import { CharCounter, ErrorText } from "./fields";

type Device = "desktop" | "phone";

export function CtaSection() {
  const { values, setField, applyValues, errors, defaults } = useBlogEditor();
  const [device, setDevice] = useState<Device>("desktop");
  const disabled = !values.ctaEnabled;
  const isBadge = values.ctaButtonStyle === "APP_STORE";

  const resetToDefaults = () =>
    applyValues({
      ctaTitle: defaults.ctaTitle,
      ctaDescription: defaults.ctaDescription,
      ctaButtonText: defaults.ctaButtonText,
      ctaButtonUrl: defaults.ctaButtonUrl,
      ctaButtonStyle: inferCtaButtonStyle(defaults.ctaButtonUrl),
      ctaImage: defaults.ctaImage ?? "",
    });

  // Switching style swaps in a matching label and link, but keeps anything the editor typed.
  const chooseStyle = (style: CtaButtonStyle) => {
    if (style === values.ctaButtonStyle) return;
    const patch: Partial<BlogFormValues> = { ctaButtonStyle: style };
    const text = values.ctaButtonText.trim();
    if (style === "APP_STORE") {
      if (!text || text === defaults.ctaButtonText) patch.ctaButtonText = APP_STORE_BADGE_LABEL;
      if (!isAppStoreUrl(values.ctaButtonUrl)) patch.ctaButtonUrl = APP_STORE_URL;
    } else {
      if (!text || text === APP_STORE_BADGE_LABEL) patch.ctaButtonText = defaults.ctaButtonText;
      if (isAppStoreUrl(values.ctaButtonUrl) && !isAppStoreUrl(defaults.ctaButtonUrl)) {
        patch.ctaButtonUrl = defaults.ctaButtonUrl;
      }
    }
    applyValues(patch);
  };

  return (
    <div className="grid gap-6">
      <Card size="sm">
        <CardContent>
          <label className="flex items-center justify-between gap-4 text-sm">
            <span>
              <span className="block font-medium">Show a call to action</span>
              <span className="text-muted-foreground">
                A card beside the article that invites readers to get the app. It stays in view while they scroll.
              </span>
            </span>
            <Switch checked={values.ctaEnabled} onCheckedChange={(checked) => setField("ctaEnabled", checked)} />
          </label>
        </CardContent>
      </Card>

      <div
        className={cn(
          "grid items-start gap-6 xl:grid-cols-[minmax(0,1fr)_25rem]",
          disabled && "pointer-events-none opacity-50",
        )}
        aria-disabled={disabled}
      >
        <Card>
          <CardHeader className="flex flex-row items-start justify-between gap-4">
            <div>
              <CardTitle>Card content</CardTitle>
              <CardDescription>Keep it short and specific to the article.</CardDescription>
            </div>
            <Button type="button" variant="ghost" size="sm" onClick={resetToDefaults} disabled={disabled}>
              <RotateCcwIcon />
              Use defaults
            </Button>
          </CardHeader>
          <CardContent className="grid gap-6">
            <Field>
              <div className="flex items-baseline justify-between">
                <FieldLabel htmlFor="cta-title">Title</FieldLabel>
                <CharCounter value={values.ctaTitle} recommended={45} max={120} />
              </div>
              <Input
                id="cta-title"
                value={values.ctaTitle}
                maxLength={120}
                disabled={disabled}
                aria-invalid={Boolean(errors.ctaTitle) || undefined}
                placeholder="Get your second number today"
                onChange={(event) => setField("ctaTitle", event.target.value)}
              />
              <ErrorText message={errors.ctaTitle} />
            </Field>

            <Field>
              <div className="flex items-baseline justify-between">
                <FieldLabel htmlFor="cta-description">Description</FieldLabel>
                <CharCounter value={values.ctaDescription} recommended={110} max={300} />
              </div>
              <Textarea
                id="cta-description"
                value={values.ctaDescription}
                maxLength={300}
                rows={3}
                disabled={disabled}
                placeholder="Stay professional, protect your privacy, and manage everything from one phone."
                onChange={(event) => setField("ctaDescription", event.target.value)}
              />
              <FieldDescription>One sentence fits the card best.</FieldDescription>
            </Field>

            <fieldset className="grid gap-3">
              <legend className="mb-3 text-sm font-medium">Button</legend>
              <RadioGroup
                value={values.ctaButtonStyle}
                onValueChange={(style) => chooseStyle(style as CtaButtonStyle)}
                className="grid gap-3 sm:grid-cols-2"
                disabled={disabled}
              >
                <StyleOption
                  value="APP_STORE"
                  selected={isBadge}
                  title="App Store badge"
                  description="Apple's download badge, as on the website."
                  sample={<AppStoreBadge className="h-8 w-[6.75rem] gap-1 rounded-md px-2 [&_svg]:size-4" compact />}
                />
                <StyleOption
                  value="BUTTON"
                  selected={!isBadge}
                  title="Text button"
                  description="Your own wording, linking anywhere."
                  sample={
                    <span className="inline-flex h-8 items-center gap-1 rounded-md bg-[#5B2C9F] px-3 text-xs font-semibold text-white">
                      Get the app
                      <ArrowRightIcon className="size-3" />
                    </span>
                  }
                />
              </RadioGroup>

              {isBadge ? (
                <div className="grid gap-5 sm:grid-cols-[1.4fr_1fr]">
                  <Field>
                    <FieldLabel htmlFor="cta-button-url">App Store link</FieldLabel>
                    <Input
                      id="cta-button-url"
                      value={values.ctaButtonUrl}
                      maxLength={500}
                      disabled={disabled}
                      aria-invalid={Boolean(errors.ctaButtonUrl) || undefined}
                      placeholder={APP_STORE_URL}
                      onChange={(event) => setField("ctaButtonUrl", event.target.value)}
                    />
                    {values.ctaButtonUrl.trim() !== APP_STORE_URL && !errors.ctaButtonUrl && (
                      <Button
                        type="button"
                        variant="link"
                        size="sm"
                        className="h-auto justify-start p-0"
                        onClick={() => setField("ctaButtonUrl", APP_STORE_URL)}
                      >
                        <LinkIcon />
                        Use the Wi-Fi Calling & Texting app link
                      </Button>
                    )}
                    <ErrorText message={errors.ctaButtonUrl} />
                  </Field>
                  <Field>
                    <FieldLabel htmlFor="cta-button-text">Badge label</FieldLabel>
                    <Input
                      id="cta-button-text"
                      value={values.ctaButtonText}
                      maxLength={40}
                      disabled={disabled}
                      aria-invalid={Boolean(errors.ctaButtonText) || undefined}
                      placeholder={APP_STORE_BADGE_LABEL}
                      onChange={(event) => setField("ctaButtonText", event.target.value)}
                    />
                    <FieldDescription>Read out by screen readers.</FieldDescription>
                    <ErrorText message={errors.ctaButtonText} />
                  </Field>
                </div>
              ) : (
                <div className="grid gap-5 sm:grid-cols-[1fr_1.4fr]">
                  <Field>
                    <div className="flex items-baseline justify-between">
                      <FieldLabel htmlFor="cta-button-text">Button text</FieldLabel>
                      <CharCounter value={values.ctaButtonText} recommended={24} max={40} />
                    </div>
                    <Input
                      id="cta-button-text"
                      value={values.ctaButtonText}
                      maxLength={40}
                      disabled={disabled}
                      aria-invalid={Boolean(errors.ctaButtonText) || undefined}
                      placeholder="Get the app"
                      onChange={(event) => setField("ctaButtonText", event.target.value)}
                    />
                    <ErrorText message={errors.ctaButtonText} />
                  </Field>
                  <Field>
                    <FieldLabel htmlFor="cta-button-url">Button URL</FieldLabel>
                    <Input
                      id="cta-button-url"
                      value={values.ctaButtonUrl}
                      maxLength={500}
                      disabled={disabled}
                      aria-invalid={Boolean(errors.ctaButtonUrl) || undefined}
                      placeholder="https://… or /path/"
                      onChange={(event) => setField("ctaButtonUrl", event.target.value)}
                    />
                    <ErrorText message={errors.ctaButtonUrl} />
                  </Field>
                </div>
              )}
            </fieldset>

            <Field>
              <FieldLabel>Image</FieldLabel>
              <ImageField
                idPrefix="cta-image"
                value={values.ctaImage ? { url: values.ctaImage, alt: "", title: "" } : null}
                onChange={(image) => setField("ctaImage", image?.url ?? "")}
                recommended={{ width: 720, height: 520 }}
                aspect="card"
                className="max-w-sm"
              />
              <FieldDescription>
                Optional. A landscape photo of someone using the app works well. It sits above the text on desktop
                and below it on tablets and phones.
              </FieldDescription>
            </Field>
          </CardContent>
        </Card>

        <div className="xl:sticky xl:top-28">
          <div className="mb-3 flex items-center justify-between gap-3">
            <p className="text-sm font-medium text-muted-foreground">Preview</p>
            <ToggleGroup
              type="single"
              variant="outline"
              size="sm"
              value={device}
              onValueChange={(value) => value && setDevice(value as Device)}
              aria-label="Preview size"
            >
              <DeviceToggle value="desktop" icon={MonitorIcon} label="Desktop" />
              <DeviceToggle value="phone" icon={SmartphoneIcon} label="Phone" />
            </ToggleGroup>
          </div>
          <div className="grid place-items-center rounded-2xl border bg-muted/40 bg-[radial-gradient(circle,rgb(15_23_42/0.06)_1px,transparent_1px)] [background-size:16px_16px] px-4 py-6">
            <CtaCardPreview values={values} device={device} />
          </div>
          <p className="mt-3 text-xs text-muted-foreground">
            {device === "desktop"
              ? "Desktop (wider than 992px): the right-hand column beside the article, sticky while reading."
              : "Tablets and phones: after the article, with the text above the image."}{" "}
            The website draws the final card.
          </p>
        </div>
      </div>
    </div>
  );
}

function StyleOption({
  value,
  selected,
  title,
  description,
  sample,
}: {
  value: CtaButtonStyle;
  selected: boolean;
  title: string;
  description: string;
  sample: ReactNode;
}) {
  return (
    <label
      className={cn(
        "flex cursor-pointer gap-3 rounded-xl border p-3.5 transition-colors hover:bg-muted/40",
        selected && "border-primary/40 bg-accent/60 hover:bg-accent/60",
      )}
    >
      <RadioGroupItem value={value} className="mt-0.5" />
      <span className="grid min-w-0 gap-2.5">
        <span>
          <span className="block text-sm font-medium">{title}</span>
          <span className="block text-xs text-muted-foreground">{description}</span>
        </span>
        <span aria-hidden="true">{sample}</span>
      </span>
    </label>
  );
}

function DeviceToggle({ value, icon: Icon, label }: { value: Device; icon: LucideIcon; label: string }) {
  return (
    <ToggleGroupItem value={value} aria-label={label} className="gap-1.5 px-2.5">
      <Icon />
      <span className="hidden sm:inline">{label}</span>
    </ToggleGroupItem>
  );
}

/**
 * The WiFi Calls website's CTA card: optional image, then a lavender panel with
 * the app icon, title, description and the button. Desktop: sticky in the column
 * beside the article. Phones: below the article.
 */
function CtaCardPreview({ values, device }: { values: BlogFormValues; device: Device }) {
  const phone = device === "phone";
  // Mirrors the WiFi Calls website's article card (.x-post-cta in src/styles/site-x.css).
  return (
    <div
      className={cn(
        "flex w-full flex-col overflow-hidden rounded-[20px] border border-[#ECE6F6] bg-[#EDE4FB] font-[-apple-system,BlinkMacSystemFont,'Segoe_UI',system-ui,Roboto,sans-serif] shadow-[0_12px_32px_-16px_rgb(91_44_159/0.35)] transition-[max-width] duration-300",
        phone ? "max-w-[20rem]" : "max-w-[22.5rem]",
      )}
    >
      {values.ctaImage && (
        // eslint-disable-next-line @next/next/no-img-element -- preview of an uploaded image
        <img src={values.ctaImage} alt="" className="aspect-[18/13] w-full object-cover" />
      )}
      <div className={cn("flex flex-col", phone ? "gap-3 p-5" : "gap-4 p-[26px]")}>
        {/* eslint-disable-next-line @next/next/no-img-element -- the WiFi Calls app icon */}
        <img
          src="/wificalls-icon.png"
          alt=""
          className={cn("rounded-[22.5%] shadow-[0_6px_18px_rgb(91_44_159/0.28)]", phone ? "size-12" : "size-[52px]")}
        />
        <p
          className={cn(
            "font-bold tracking-[-0.02em] break-words text-[#1A1233]",
            phone ? "text-[21px] leading-7" : "text-[22px] leading-[30px]",
            !values.ctaTitle && "text-[#1A1233]/30",
          )}
        >
          {values.ctaTitle || "Card title"}
        </p>
        {values.ctaDescription && (
          <p className={cn("-mt-1 break-words text-[#453B60]", phone ? "text-[15px] leading-6" : "text-base leading-[26px]")}>
            {values.ctaDescription}
          </p>
        )}
        <div className="pt-1">
          {values.ctaButtonStyle === "APP_STORE" ? (
            <AppStoreBadge />
          ) : (
            <span className="inline-flex h-12 max-w-full items-center gap-2 rounded-xl bg-[#5B2C9F] px-6 text-[15.5px] font-semibold text-white shadow-[0_8px_20px_-8px_rgb(91_44_159/0.6)]">
              <span className="truncate">{values.ctaButtonText || "Button"}</span>
              <ArrowRightIcon className="size-4 shrink-0" />
            </span>
          )}
        </div>
      </div>
    </div>
  );
}

/** A drawing of Apple's "Download on the App Store" badge (the website uses Apple's artwork). */
function AppStoreBadge({ className, compact = false }: { className?: string; compact?: boolean }) {
  return (
    <span
      className={cn(
        "inline-flex h-12 w-40 items-center gap-2 rounded-[9px] border border-[#a6a6a6] bg-black px-3 text-white",
        className,
      )}
    >
      <svg viewBox="0 0 24 24" className="size-7 shrink-0 fill-current" aria-hidden="true">
        <path d="M15.53 3.83c.84-1.01 1.4-2.43 1.25-3.83-1.21.05-2.67.8-3.53 1.82-.78.9-1.46 2.34-1.27 3.71 1.34.1 2.71-.69 3.55-1.7zM12.15 6.9c-.95 0-2.42-1.08-3.96-1.04-2.04.03-3.91 1.18-4.96 3.01-2.12 3.68-.55 9.1 1.52 12.09 1.01 1.45 2.2 3.09 3.79 3.04 1.52-.07 2.09-.99 3.93-.99 1.83 0 2.35.99 3.96.95 1.64-.03 2.68-1.48 3.68-2.95 1.15-1.69 1.63-3.33 1.66-3.42-.04-.01-3.18-1.22-3.22-4.86-.03-3.04 2.48-4.49 2.6-4.56-1.43-2.09-3.63-2.32-4.39-2.38-2-.15-3.68 1.09-4.61 1.09z" />
      </svg>
      <span className="flex flex-col leading-none">
        <span className={cn("font-medium tracking-wide", compact ? "text-[7px]" : "text-[10px]")}>Download on the</span>
        <span className={cn("font-semibold tracking-tight", compact ? "text-[13px]" : "mt-0.5 text-[21px]")}>
          App Store
        </span>
      </span>
    </span>
  );
}
