"use client";

import * as React from "react";
import { cn } from "@/lib/utils";
import { FormField, InputField, TextareaField } from "./FormField";
import { ImageUploadInput } from "./ImageUploadInput";
import type { ProductFormData } from "../../types/product-form";

interface SEOSectionProps {
  data: ProductFormData;
  onChange: (data: Partial<ProductFormData>) => void;
  errors?: Partial<Record<keyof ProductFormData, string>>;
  autoGenerateFromName?: string;
}

export function SEOSection({
  data,
  onChange,
  errors = {},
  autoGenerateFromName = "",
}: SEOSectionProps) {
  const handleNestedChange = <T extends object>(
    parentField: keyof ProductFormData,
    nestedField: keyof T,
    value: unknown
  ) => {
    const current = data[parentField] as T;
    onChange({
      [parentField]: { ...current, [nestedField]: value },
    } as Partial<ProductFormData>);
  };

  const [metaKeywords, setMetaKeywords] = React.useState<string[]>(
    data.seo.metaKeywords || []
  );

  const handleKeywordsChange = (keywords: string[]) => {
    setMetaKeywords(keywords);
    handleNestedChange("seo", "metaKeywords", keywords);
  };

  const addKeyword = (keyword: string) => {
    const trimmed = keyword.trim();
    if (trimmed && !metaKeywords.includes(trimmed)) {
      handleKeywordsChange([...metaKeywords, trimmed]);
    }
  };

  const removeKeyword = (keyword: string) => {
    handleKeywordsChange(metaKeywords.filter((k) => k !== keyword));
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if ((e.key === "Enter" || e.key === ",") && e.currentTarget.value.trim()) {
      e.preventDefault();
      addKeyword(e.currentTarget.value);
      e.currentTarget.value = "";
    }
  };

  // Auto-generate meta title and description from product name
  const generateMetaTitle = () => {
    if (autoGenerateFromName) {
      return `${autoGenerateFromName} | S.I. Tech Hub`;
    }
    return data.name ? `${data.name} | S.I. Tech Hub` : "";
  };

  const generateMetaDescription = () => {
    if (data.description.overview) {
      return data.description.overview.slice(0, 155);
    }
    if (autoGenerateFromName) {
      return `Buy ${autoGenerateFromName} at S.I. Tech Hub. Best prices, fast shipping, and genuine products.`;
    }
    return "";
  };

  return (
    <div className="space-y-6">
      {/* Meta Title */}
      <FormField
        label="Meta Title"
        description="Page title for search results (max 60 characters recommended)"
        error={errors.seo as string}
      >
        <InputField
          label=""
          value={data.seo.metaTitle || generateMetaTitle()}
          onChange={(e) => handleNestedChange("seo", "metaTitle", e.target.value)}
          placeholder="Auto-generated from product name"
          maxLength={70}
          className="font-mono text-sm"
        />
        <div className="flex items-center justify-between mt-1">
          <span className="text-xs text-muted-foreground">
            {data.seo.metaTitle?.length || 0}/70 characters
          </span>
          <button
            type="button"
            onClick={() => handleNestedChange("seo", "metaTitle", generateMetaTitle())}
            className="text-xs text-primary hover:text-primary/80"
          >
            Auto-generate
          </button>
        </div>
      </FormField>

      {/* Meta Description */}
      <FormField
        label="Meta Description"
        description="Description for search results (max 160 characters recommended)"
        error={errors.seo as string}
      >
        <TextareaField
          label=""
          value={data.seo.metaDescription || generateMetaDescription()}
          onChange={(e) => handleNestedChange("seo", "metaDescription", e.target.value)}
          placeholder="Auto-generated from product overview"
          rows={3}
          maxLength={160}
          className="font-mono text-sm"
        />
        <div className="flex items-center justify-between mt-1">
          <span className="text-xs text-muted-foreground">
            {data.seo.metaDescription?.length || 0}/160 characters
          </span>
          <button
            type="button"
            onClick={() => handleNestedChange("seo", "metaDescription", generateMetaDescription())}
            className="text-xs text-primary hover:text-primary/80"
          >
            Auto-generate
          </button>
        </div>
      </FormField>

      {/* Meta Keywords */}
      <FormField
        label="Meta Keywords"
        description="Comma-separated keywords for SEO (optional)"
      >
        <div className="space-y-2">
          <div className="flex flex-wrap gap-2">
            {metaKeywords.map((keyword) => (
              <span
                key={keyword}
                className="inline-flex items-center gap-1.5 rounded-full bg-primary/10 text-primary px-2.5 py-1 text-sm"
              >
                {keyword}
                <button
                  type="button"
                  onClick={() => removeKeyword(keyword)}
                  className="p-0.5 rounded-full hover:bg-primary/20 transition-colors"
                  aria-label={`Remove keyword: ${keyword}`}
                >
                  <svg className="h-3 w-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </span>
            ))}
            <input
              type="text"
              placeholder="Add keyword, press Enter..."
              onKeyDown={handleKeyDown}
              className="flex-1 min-w-[150px] h-9 px-3 py-1.5 text-sm border border-input bg-input/30 rounded-4xl focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"
            />
          </div>
          <p className="text-xs text-muted-foreground">
            Press Enter or comma to add keywords. These are used by search engines.
          </p>
        </div>
      </FormField>

      {/* Open Graph / Social Sharing */}
      <div className="pt-6 border-t border-border">
        <h4 className="text-lg font-medium text-foreground mb-4">Open Graph / Social Sharing</h4>

        <TextareaField
          label="OG Title"
          description="Title shown when shared on social media"
          value={data.seo.ogTitle || ""}
          onChange={(e) => handleNestedChange("seo", "ogTitle", e.target.value)}
          rows={2}
          placeholder="Defaults to meta title"
        />

        <TextareaField
          label="OG Description"
          description="Description shown when shared on social media"
          value={data.seo.ogDescription || ""}
          onChange={(e) => handleNestedChange("seo", "ogDescription", e.target.value)}
          rows={3}
          placeholder="Defaults to meta description"
        />

        <FormField
          label="OG Image"
          description="Image shown when shared on social media (1200x630 recommended)"
        >
          <ImageUploadInput
            value={data.seo.ogImage}
            onChange={(v) => handleNestedChange("seo", "ogImage", v ?? undefined)}
          />
        </FormField>
      </div>

      {/* Advanced SEO */}
      <div className="pt-6 border-t border-border">
        <h4 className="text-lg font-medium text-foreground mb-4">Advanced SEO</h4>

        <InputField
          label="Canonical URL"
          description="Canonical URL to prevent duplicate content issues"
          value={data.seo.canonicalUrl || ""}
          onChange={(e) => handleNestedChange("seo", "canonicalUrl", e.target.value)}
          placeholder="https://example.com/product/slug"
          type="url"
        />

        <div className="rounded-lg bg-muted/50 p-4 border border-border">
          <p className="text-sm text-muted-foreground">
            <strong>Note:</strong> The canonical URL is typically auto-generated from the product slug.
            Only override if you have a specific reason to point to a different URL.
          </p>
        </div>
      </div>
    </div>
  );
}