import { useState, type CSSProperties } from "react"
import { resolveGlobalColor } from "@/components/ui/global-color-picker"
import { resolveGlobalTypography } from "@/components/ui/global-typography-picker"
import type {
  AppearanceSettings,
  BehaviorSettings,
  ContentSettings,
  CookieCategory,
} from "../types"

type CookieConsentStyle = CSSProperties & Record<`--swift-commerce-cookie-consent-${string}`, string | number>

interface CookieConsentPreviewProps {
  settings: AppearanceSettings
  behaviorSettings: BehaviorSettings
  contentSettings: ContentSettings
  categories: CookieCategory[]
}

const shieldIcon = (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
    <path d="M9 12l2 2 4-4" />
  </svg>
)

export function CookieConsentPreview({
  settings,
  behaviorSettings,
  contentSettings,
  categories,
}: CookieConsentPreviewProps) {
  const [preferencesOpen, setPreferencesOpen] = useState(false)
  const isMagazine = settings.template === "magazine"
  const requiredCount = categories.filter((category) => category.required).length
  const optionalCount = Math.max(0, categories.length - requiredCount)
  const globalStyles = (window as any).swiftCommerceData?.globalStyles
  const hasGlobalColor = (id: string) => Boolean(globalStyles?.colors?.some((color: { id: string }) => color.id === id))
  const hasGlobalTypography = (id: string) => Boolean(globalStyles?.typography?.some((typography: { id: string }) => typography.id === id))

  const style: CookieConsentStyle = {
    "--swift-commerce-cookie-consent-overlay-color": settings.overlayColor || "#000000",
    "--swift-commerce-cookie-consent-overlay-opacity": settings.overlay ? (settings.overlayOpacity || 0) / 100 : 0,
    "--swift-commerce-cookie-consent-title-size": `${settings.titleFontSize || 16}px`,
    "--swift-commerce-cookie-consent-body-size": `${settings.bodyFontSize || 14}px`,
    "--swift-commerce-cookie-consent-font-weight": settings.fontWeight || "400",
    "--swift-commerce-cookie-consent-boxed-width": `${settings.boxedWidth || 80}%`,
  }

  if (settings.primaryColor || hasGlobalColor("primary")) {
    style["--swift-commerce-cookie-consent-primary"] = resolveGlobalColor(settings.primaryColor, "primary", "#00226b")
  }
  if (settings.backgroundColor || hasGlobalColor("background")) {
    style["--swift-commerce-cookie-consent-background"] = resolveGlobalColor(settings.backgroundColor, "background", "#ffffff")
  }
  if (settings.textColor || hasGlobalColor("text")) {
    const textColor = resolveGlobalColor(settings.textColor, "text", "#1f2937")
    style["--swift-commerce-cookie-consent-text"] = textColor
    style["--swift-commerce-cookie-consent-muted"] = textColor
  }
  if (settings.acceptButtonColor) {
    style["--swift-commerce-cookie-consent-accept-background"] = settings.acceptButtonColor
  }
  if (settings.acceptButtonTextColor) {
    style["--swift-commerce-cookie-consent-accept-text"] = settings.acceptButtonTextColor
  }
  if (settings.declineButtonColor) {
    style["--swift-commerce-cookie-consent-decline"] = settings.declineButtonColor
  }
  if ((settings.fontFamily && settings.fontFamily !== "inherit") || hasGlobalTypography("body")) {
    style["--swift-commerce-cookie-consent-font-family"] = resolveGlobalTypography(settings.fontFamily, "body", "inherit")
  }
  style["--swift-commerce-cookie-consent-radius"] = `${settings.borderRadius || 0}px`

  const classes = [
    "swift-commerce-ui",
    "swift-commerce-cookie-consent",
    "swift-commerce-cookie-consent--preview",
    "is-visible",
    `swift-commerce-cookie-consent--template-${settings.template}`,
    `swift-commerce-cookie-consent--position-${settings.position}`,
    `swift-commerce-cookie-consent--layout-${settings.layout}`,
    `swift-commerce-cookie-consent--theme-${settings.theme}`,
    `swift-commerce-cookie-consent--animation-${settings.animation}`,
    `swift-commerce-cookie-consent--buttons-${settings.buttonStyle}`,
    `swift-commerce-cookie-consent--buttons-${settings.buttonSize}`,
    `swift-commerce-cookie-consent--decline-${settings.declineButtonStyle}`,
    `swift-commerce-cookie-consent--settings-${settings.settingsButtonStyle}`,
    settings.showIcon && !isMagazine ? "swift-commerce-cookie-consent--has-icon" : "",
    settings.overlayBlur || settings.blur ? "swift-commerce-cookie-consent--overlay-blur" : "",
  ].filter(Boolean).join(" ")

  return (
    <>
      <div className={classes} style={style} role="dialog" aria-label="Cookie consent preview">
        <div className="swift-commerce-cookie-consent__surface">
          <div className="swift-commerce-cookie-consent__primary" data-cookie-consent-primary hidden={preferencesOpen}>
            {settings.showIcon && !isMagazine && (
              <div className="swift-commerce-cookie-consent__icon" aria-hidden="true">
                {shieldIcon}
              </div>
            )}

            <div className="swift-commerce-cookie-consent__content">
              {isMagazine && (
                <span className="swift-commerce-cookie-consent__eyebrow">Privacy Notice</span>
              )}
              <h3 className="swift-commerce-heading swift-commerce-cookie-consent__title">
                {contentSettings.title || "We Value Your Privacy"}
              </h3>
              <p className="swift-commerce-copy swift-commerce-cookie-consent__message">
                {contentSettings.message || "We use cookies to enhance your browsing experience."}
                {contentSettings.showPrivacyLink && contentSettings.privacyPolicyUrl && (
                  <a
                    href={contentSettings.privacyPolicyUrl}
                    className="swift-commerce-link swift-commerce-cookie-consent__privacy-link"
                    onClick={(event) => event.preventDefault()}
                  >
                    {contentSettings.privacyPolicyText || "Privacy Policy"}
                  </a>
                )}
              </p>

              {isMagazine && (
                <div className="swift-commerce-cookie-consent__stats" aria-label="Cookie category summary">
                  <span className="swift-commerce-cookie-consent__stat">
                    <strong className="swift-commerce-cookie-consent__stat-number">{categories.length}</strong>
                    <span className="swift-commerce-cookie-consent__stat-label">Categories</span>
                  </span>
                  <span className="swift-commerce-cookie-consent__stat">
                    <strong className="swift-commerce-cookie-consent__stat-number">{optionalCount}</strong>
                    <span className="swift-commerce-cookie-consent__stat-label">Optional</span>
                  </span>
                  <span className="swift-commerce-cookie-consent__stat">
                    <strong className="swift-commerce-cookie-consent__stat-number">{requiredCount}</strong>
                    <span className="swift-commerce-cookie-consent__stat-label">Required</span>
                  </span>
                </div>
              )}
            </div>

            <div className="swift-commerce-cookie-consent__actions">
              <button type="button" className="swift-commerce-button swift-commerce-cookie-consent__button swift-commerce-cookie-consent__button--accept">
                {contentSettings.acceptButtonText || "Accept All"}
              </button>
              <button type="button" className="swift-commerce-button swift-commerce-button--secondary swift-commerce-cookie-consent__button swift-commerce-cookie-consent__button--decline">
                {contentSettings.declineButtonText || "Decline"}
              </button>
              <button
                type="button"
                className="swift-commerce-button swift-commerce-button--ghost swift-commerce-cookie-consent__button swift-commerce-cookie-consent__button--settings"
                aria-expanded={preferencesOpen}
                onClick={() => setPreferencesOpen(true)}
              >
                {contentSettings.settingsButtonText || "Cookie Settings"}
              </button>
              {isMagazine && (
                <p className="swift-commerce-cookie-consent__footer-note">
                  You can change your preferences at any time.
                </p>
              )}
            </div>
          </div>

          <div className="swift-commerce-cookie-consent__preferences" hidden={!preferencesOpen}>
            <div className="swift-commerce-cookie-consent__preferences-header">
              <h4 className="swift-commerce-cookie-consent__preferences-title">Cookie Settings</h4>
              <button
                type="button"
                className="swift-commerce-icon-button swift-commerce-cookie-consent__close"
                aria-label="Close cookie settings"
                onClick={() => setPreferencesOpen(false)}
              >
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M18 6L6 18M6 6l12 12" />
                </svg>
              </button>
            </div>
            <div className="swift-commerce-cookie-consent__categories">
              {categories.map((category) => (
                <div className="swift-commerce-cookie-consent__category" key={category.id}>
                  <label className="swift-commerce-cookie-consent__category-label">
                    <input
                      className="swift-commerce-cookie-consent__category-checkbox"
                      type="checkbox"
                      defaultChecked={category.required || category.enabled}
                      disabled={category.required}
                    />
                    <span className="swift-commerce-cookie-consent__category-name">
                      {category.name}
                      {category.required && (
                        <span className="swift-commerce-cookie-consent__required">(Required)</span>
                      )}
                    </span>
                  </label>
                  <p className="swift-commerce-cookie-consent__category-description">
                    {category.description}
                  </p>
                </div>
              ))}
            </div>
            <div className="swift-commerce-cookie-consent__preferences-actions">
              <button
                type="button"
                className="swift-commerce-button swift-commerce-cookie-consent__button swift-commerce-cookie-consent__button--accept"
                onClick={() => setPreferencesOpen(false)}
              >
                Save Preferences
              </button>
            </div>
          </div>
        </div>
      </div>

      {behaviorSettings.reopenMethod === "floating-button" && (
        <button
          type="button"
          className={`swift-commerce-ui swift-commerce-icon-button swift-commerce-cookie-consent-reopen swift-commerce-cookie-consent-reopen--floating swift-commerce-cookie-consent-reopen--${behaviorSettings.floatingButtonPosition} swift-commerce-cookie-consent-preview-reopen`}
          style={{ "--swift-commerce-cookie-consent-primary": settings.primaryColor || "var(--swift-commerce-color-primary)" } as CookieConsentStyle}
          aria-label="Cookie Settings"
        >
          {shieldIcon}
        </button>
      )}
    </>
  )
}
