"use client";

import {
  CircleAlertIcon,
  CircleCheckIcon,
  CircleXIcon,
  GlobeIcon,
  MonitorIcon,
  SmartphoneIcon,
} from "lucide-react";
import { useDeferredValue, useMemo, useState } from "react";

import { ImageField } from "@/components/media/image-field";
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 { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import {
  analyzeSeo,
  META_DESCRIPTION_MAX,
  META_DESCRIPTION_MIN,
  SEO_TITLE_MAX,
  seoScore,
} from "@/features/seo/analysis";
import { FEATURED_IMAGE_SIZE } from "@/lib/media/constants";
import { cn } from "@/lib/utils";

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

const BRAND = "Wi-Fi Calling & Texting";

function wordCount(html: string) {
  return html
    .replace(/<[^>]+>/g, " ")
    .replace(/&[a-z#0-9]+;/gi, " ")
    .split(/\s+/)
    .filter(Boolean).length;
}

function truncate(text: string, max: number) {
  return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
}

export function SeoSection() {
  const { values, setField, errors, siteUrl } = useBlogEditor();
  const [device, setDevice] = useState<"desktop" | "mobile">("desktop");

  const host = siteUrl ? new URL(siteUrl).host : "wifi-calls-web.vercel.app";
  const effectiveTitle = values.seoTitle || values.title || "Article title";
  const effectiveDescription =
    values.metaDescription || values.excerpt || "Add a meta description to control the snippet search engines show.";
  const defaultUrl = `${siteUrl ?? "https://wifi-calls-web.vercel.app"}/blog/${values.slug || "url-slug"}/`;

  // This section is always on the page, so analyse a deferred copy to keep typing in the body smooth.
  const deferred = useDeferredValue(values);
  const checks = useMemo(
    () =>
      analyzeSeo({
        title: deferred.title,
        slug: deferred.slug,
        excerpt: deferred.excerpt,
        wordCount: wordCount(deferred.content),
        seoTitle: deferred.seoTitle || null,
        metaDescription: deferred.metaDescription || null,
        focusKeyword: deferred.focusKeyword || null,
        featuredImage: deferred.featuredImage || null,
        featuredImageAlt: deferred.featuredImageAlt || null,
        robotsIndex: deferred.robotsIndex,
        canonicalUrl: deferred.canonicalUrl || null,
      }),
    [deferred],
  );
  const score = seoScore(checks);

  return (
    <div className="grid gap-6">
      <Card>
        <CardHeader className="flex flex-row items-start justify-between gap-4">
          <div>
            <CardTitle>Search result preview</CardTitle>
            <CardDescription>How this article may appear on Google.</CardDescription>
          </div>
          <ToggleGroup
            type="single"
            variant="outline"
            size="sm"
            value={device}
            onValueChange={(value) => value && setDevice(value as typeof device)}
            aria-label="Preview device"
          >
            <ToggleGroupItem value="desktop" aria-label="Desktop">
              <MonitorIcon />
            </ToggleGroupItem>
            <ToggleGroupItem value="mobile" aria-label="Mobile">
              <SmartphoneIcon />
            </ToggleGroupItem>
          </ToggleGroup>
        </CardHeader>
        <CardContent>
          <div
            className={cn(
              "rounded-xl border bg-white p-4 font-[Arial,sans-serif]",
              device === "mobile" ? "max-w-[380px]" : "max-w-[640px]",
            )}
          >
            <div className="flex items-center gap-3">
              <span className="grid size-7 place-items-center rounded-full bg-[#f1f3f4]">
                <GlobeIcon className="size-4 text-[#5b2c9f]" />
              </span>
              <div className="min-w-0 leading-tight">
                <p className="text-sm text-[#202124]">{BRAND}</p>
                <p className="truncate text-xs text-[#4d5156]">
                  https://{host} › blog › {values.slug || "url-slug"}
                </p>
              </div>
            </div>
            <p
              className={cn(
                "mt-2 leading-snug text-[#1a0dab]",
                device === "mobile" ? "text-lg" : "text-xl",
              )}
            >
              {truncate(effectiveTitle, device === "mobile" ? 70 : SEO_TITLE_MAX)}
            </p>
            <p className="mt-1 text-sm leading-relaxed text-[#4d5156]">
              {truncate(effectiveDescription, device === "mobile" ? 120 : META_DESCRIPTION_MAX)}
            </p>
          </div>
        </CardContent>
      </Card>

      <div className="grid gap-6 xl:grid-cols-[1fr_300px]">
        <Card>
          <CardHeader>
            <CardTitle>Search engine listing</CardTitle>
          </CardHeader>
          <CardContent className="grid gap-5">
            <Field>
              <div className="flex items-baseline justify-between">
                <FieldLabel htmlFor="seo-title">SEO title</FieldLabel>
                <CharCounter value={values.seoTitle || values.title} recommended={SEO_TITLE_MAX} max={120} />
              </div>
              <Input
                id="seo-title"
                value={values.seoTitle}
                maxLength={120}
                placeholder={values.title || "Defaults to the article title"}
                onChange={(event) => setField("seoTitle", event.target.value)}
              />
              <FieldDescription>Keep it under {SEO_TITLE_MAX} characters so it isn&apos;t cut off.</FieldDescription>
              <ErrorText message={errors.seoTitle} />
            </Field>

            <Field>
              <div className="flex items-baseline justify-between">
                <FieldLabel htmlFor="seo-description">Meta description</FieldLabel>
                <CharCounter
                  value={values.metaDescription}
                  recommended={META_DESCRIPTION_MAX}
                  min={META_DESCRIPTION_MIN}
                  max={320}
                />
              </div>
              <Textarea
                id="seo-description"
                value={values.metaDescription}
                maxLength={320}
                rows={3}
                placeholder={values.excerpt || "Summarize the article for search results"}
                onChange={(event) => setField("metaDescription", event.target.value)}
              />
              <FieldDescription>
                {META_DESCRIPTION_MIN}–{META_DESCRIPTION_MAX} characters works best.
              </FieldDescription>
              <ErrorText message={errors.metaDescription} />
            </Field>

            <Field>
              <FieldLabel htmlFor="seo-keyword">Focus keyword</FieldLabel>
              <Input
                id="seo-keyword"
                value={values.focusKeyword}
                maxLength={100}
                placeholder="e.g. airbnb host phone number"
                onChange={(event) => setField("focusKeyword", event.target.value)}
              />
              <FieldDescription>The URL slug is edited under the article title.</FieldDescription>
            </Field>

            <Field>
              <FieldLabel htmlFor="seo-canonical">Canonical URL</FieldLabel>
              <Input
                id="seo-canonical"
                value={values.canonicalUrl}
                type="url"
                placeholder={defaultUrl}
                onChange={(event) => setField("canonicalUrl", event.target.value)}
              />
              <FieldDescription>Leave empty unless the original version of this article lives elsewhere.</FieldDescription>
              <ErrorText message={errors.canonicalUrl} />
            </Field>

            <div className="grid gap-3 rounded-lg border bg-muted/30 p-4">
              <label className="flex items-center justify-between gap-4 text-sm">
                <span>
                  <span className="block font-medium">Allow search engines to index</span>
                  <span className="text-muted-foreground">Off adds noindex; the article won&apos;t appear in search.</span>
                </span>
                <Switch checked={values.robotsIndex} onCheckedChange={(checked) => setField("robotsIndex", checked)} />
              </label>
              <label className="flex items-center justify-between gap-4 text-sm">
                <span>
                  <span className="block font-medium">Allow search engines to follow links</span>
                  <span className="text-muted-foreground">Off adds nofollow to the page.</span>
                </span>
                <Switch checked={values.robotsFollow} onCheckedChange={(checked) => setField("robotsFollow", checked)} />
              </label>
            </div>
          </CardContent>
        </Card>

        <Card className="h-fit">
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              SEO checks
              <span
                className={cn(
                  "rounded-full px-2.5 py-0.5 text-xs font-semibold tabular-nums",
                  score >= 80 ? "bg-success-soft text-success" : score >= 50 ? "bg-warning-soft text-warning" : "bg-destructive/10 text-destructive",
                )}
              >
                {score}/100
              </span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <ul className="space-y-3">
              {checks.map((check) => (
                <li key={check.id} className="flex gap-2.5 text-sm">
                  {check.status === "pass" ? (
                    <CircleCheckIcon className="mt-0.5 size-4 shrink-0 text-success" />
                  ) : check.status === "warn" ? (
                    <CircleAlertIcon className="mt-0.5 size-4 shrink-0 text-warning" />
                  ) : (
                    <CircleXIcon className="mt-0.5 size-4 shrink-0 text-destructive" />
                  )}
                  <span>
                    <span className="block font-medium">{check.label}</span>
                    <span className="text-muted-foreground">{check.message}</span>
                  </span>
                </li>
              ))}
            </ul>
            <p className="mt-5 border-t pt-4 text-xs text-muted-foreground">
              Article, breadcrumb and FAQ structured data are generated automatically on the website.
            </p>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Social sharing</CardTitle>
          <CardDescription>Used when the article is shared on social networks and messaging apps.</CardDescription>
        </CardHeader>
        <CardContent className="grid gap-6 lg:grid-cols-2">
          <div className="grid content-start gap-5">
            <Field>
              <div className="flex items-baseline justify-between">
                <FieldLabel htmlFor="og-title">Social title</FieldLabel>
                <CharCounter value={values.ogTitle} recommended={70} max={120} />
              </div>
              <Input
                id="og-title"
                value={values.ogTitle}
                maxLength={120}
                placeholder={effectiveTitle}
                onChange={(event) => setField("ogTitle", event.target.value)}
              />
            </Field>
            <Field>
              <div className="flex items-baseline justify-between">
                <FieldLabel htmlFor="og-description">Social description</FieldLabel>
                <CharCounter value={values.ogDescription} recommended={200} max={320} />
              </div>
              <Textarea
                id="og-description"
                value={values.ogDescription}
                maxLength={320}
                rows={3}
                placeholder={values.metaDescription || values.excerpt}
                onChange={(event) => setField("ogDescription", event.target.value)}
              />
            </Field>
          </div>
          <Field>
            <FieldLabel>Social image</FieldLabel>
            <ImageField
              idPrefix="og-image"
              aspect="og"
              recommended={FEATURED_IMAGE_SIZE}
              value={values.ogImage ? { url: values.ogImage, alt: "", title: "" } : null}
              onChange={(image) => setField("ogImage", image?.url ?? "")}
            />
            {!values.ogImage && values.featuredImage && (
              <FieldDescription>The featured image is used when this is empty.</FieldDescription>
            )}
            <ErrorText message={errors.ogImage} />
          </Field>
        </CardContent>
      </Card>
    </div>
  );
}
