/**
 * Shipment Tracking Appearance Tab
 *
 * Full appearance customization with live preview.
 * Follows the Product Addons Customization Tab pattern.
 * - Customize Design on the left with collapsible accordion sections
 * - Live Preview on the right (sticky)
 * - Free: Colors + Form Content
 * - Pro: Typography, Spacing & Dimensions, Layout
 */

import { useState, useMemo } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Button } from "@/components/ui/button"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible"
import { LivePreview } from "@/components/ui/live-preview"
import { ChevronDown, Code, Minus, Palette, Plus, RotateCcw } from "lucide-react"
import { ProIndicator } from "@/components/pro/pro-indicator"
import { GlobalColorPicker } from "@/components/ui/global-color-picker"
import { GlobalTypographyPicker } from "@/components/ui/global-typography-picker"
import { getAllGoogleFontsPreviewUrls } from "@/lib/google-fonts"
import { usePro } from "@/contexts/pro-context"
import {
  TrackingSettings,
  TrackingFormCustomization,
  defaultCustomization,
  quickStartPresets,
} from "../../types"

interface AppearanceTabProps {
  settings: TrackingSettings
  updateSetting: <K extends keyof TrackingSettings>(key: K, value: TrackingSettings[K]) => void
}

/* ------------------------------------------------------------------ */
/*  Reusable inline helpers                                            */
/* ------------------------------------------------------------------ */

function NumberStepper({
  label,
  value,
  onChange,
  min,
  max,
  step = 1,
  unit = 'px',
}: {
  label: string
  value: number
  onChange: (v: number) => void
  min: number
  max: number
  step?: number
  unit?: string
}) {
  const clamp = (v: number) => Math.min(max, Math.max(min, v))
  return (
    <div className="flex items-center justify-between gap-2">
      <Label className="text-sm whitespace-nowrap">{label}</Label>
      <div className="inline-flex items-center rounded-md border bg-background">
        <button
          type="button"
          onClick={() => onChange(clamp(value - step))}
          disabled={value <= min}
          className="flex items-center justify-center h-8 w-8 text-muted-foreground hover:text-foreground disabled:opacity-30 transition-colors cursor-pointer"
        >
          <Minus className="h-3 w-3" />
        </button>
        <input
          type="text"
          value={`${value}${unit}`}
          onChange={(e) => {
            const parsed = parseInt(e.target.value, 10)
            if (!isNaN(parsed)) onChange(clamp(parsed))
          }}
          className="h-8 w-14 text-center text-sm border-x bg-transparent outline-none"
        />
        <button
          type="button"
          onClick={() => onChange(clamp(value + step))}
          disabled={value >= max}
          className="flex items-center justify-center h-8 w-8 text-muted-foreground hover:text-foreground disabled:opacity-30 transition-colors cursor-pointer"
        >
          <Plus className="h-3 w-3" />
        </button>
      </div>
    </div>
  )
}

function SegmentedControl<T extends string>({
  value, onChange, options,
}: {
  value: T
  onChange: (v: T) => void
  options: { value: T; label: string }[]
}) {
  return (
    <div className="inline-flex items-center rounded-lg border bg-muted/40 p-0.5">
      {options.map(opt => (
        <button
          key={opt.value}
          type="button"
          onClick={() => onChange(opt.value)}
          className={`
            px-3 py-1.5 text-xs font-medium rounded-md transition-all cursor-pointer
            ${value === opt.value
              ? 'bg-background text-foreground shadow-sm'
              : 'text-muted-foreground hover:text-foreground'}
          `}
        >
          {opt.label}
        </button>
      ))}
    </div>
  )
}

/* ------------------------------------------------------------------ */
/*  Main component                                                     */
/* ------------------------------------------------------------------ */

export function AppearanceTab({ settings, updateSetting }: AppearanceTabProps) {
  const { isPro } = usePro()
  const c = settings.customization || defaultCustomization

  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
    content: false,
    colors: false,
    typography: false,
    spacing: false,
    layout: false,
  })

  const googleFontsUrls = useMemo(() => getAllGoogleFontsPreviewUrls(), [])

  const updateC = <K extends keyof TrackingFormCustomization>(key: K, value: TrackingFormCustomization[K]) => {
    updateSetting('customization', { ...c, [key]: value })
  }

  const resetCustomization = () => {
    updateSetting('customization', { ...defaultCustomization })
  }

  const applyPreset = (presetId: string) => {
    const preset = quickStartPresets.find(p => p.id === presetId)
    if (preset) {
      const updated = { ...c }
      Object.entries(preset.customization).forEach(([key, value]) => {
        (updated as any)[key] = value
      })
      updateSetting('customization', updated)
    }
  }

  const toggleSection = (section: string) => {
    setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }))
  }

  /* ------------------------------------------------------------------ */
  /*  Live Preview                                                       */
  /* ------------------------------------------------------------------ */
  const renderLivePreview = () => {
    const formStyle: React.CSSProperties = {
      maxWidth: `${c.formMaxWidth}px`,
      margin: c.formAlignment === 'center' ? '0 auto'
        : c.formAlignment === 'right' ? '0 0 0 auto' : '0',
      padding: `${c.formPadding * 0.75}px`,
      background: c.formBackground,
      borderRadius: `${c.formBorderRadius}px`,
      border: `1px solid ${c.formBorderColor}`,
      fontFamily: c.fontFamily || undefined,
      boxShadow: '0 1px 3px 0 rgb(0 0 0 / 0.05)',
    }

    const titleStyle: React.CSSProperties = {
      fontSize: `${c.titleFontSize * 0.85}px`,
      fontWeight: c.titleFontWeight,
      color: c.titleColor,
      textAlign: c.titleAlignment,
      marginBottom: '4px',
      fontFamily: c.fontFamily || undefined,
    }

    const descStyle: React.CSSProperties = {
      fontSize: `${c.descriptionFontSize * 0.85}px`,
      color: c.descriptionColor,
      textAlign: c.titleAlignment,
      marginBottom: `${c.fieldSpacing * 0.75}px`,
      fontFamily: c.fontFamily || undefined,
    }

    const labelStyle: React.CSSProperties = {
      display: 'block',
      fontSize: `${c.labelFontSize * 0.85}px`,
      fontWeight: c.labelFontWeight,
      color: c.labelColor,
      marginBottom: '4px',
      fontFamily: c.fontFamily || undefined,
    }

    const inputStyle: React.CSSProperties = {
      width: '100%',
      padding: `${c.inputPadding * 0.75}px`,
      border: `1px solid ${c.inputBorderColor}`,
      borderRadius: `${c.inputBorderRadius}px`,
      fontSize: `${c.inputFontSize * 0.85}px`,
      color: c.inputTextColor,
      background: c.inputBackground,
      outline: 'none',
      boxSizing: 'border-box',
      fontFamily: c.fontFamily || undefined,
    }

    const buttonStyle: React.CSSProperties = {
      width: '100%',
      padding: `${c.buttonPadding * 0.75}px`,
      background: c.buttonBackground,
      color: c.buttonTextColor,
      border: 'none',
      borderRadius: `${c.buttonBorderRadius}px`,
      fontSize: `${c.buttonFontSize * 0.85}px`,
      fontWeight: c.buttonFontWeight,
      cursor: 'pointer',
      fontFamily: c.fontFamily || undefined,
    }

    return (
      <div className="p-4">
        {googleFontsUrls.map((url, i) => (
          <link key={i} rel="stylesheet" href={url} />
        ))}
        <div
          className="transform origin-top transition-all"
          style={{ transform: 'scale(0.85)', transformOrigin: 'top center' }}
        >
          <div style={formStyle}>
            <h3 style={titleStyle}>
              {settings.form_title || 'Track Your Order'}
            </h3>
            <p style={descStyle}>
              {settings.form_description || 'Enter your tracking number below to see the delivery status of your order.'}
            </p>

            <div style={{ display: 'flex', flexDirection: 'column', gap: `${c.fieldSpacing * 0.75}px` }}>
              <div>
                <label style={labelStyle}>Tracking Number</label>
                <input
                  type="text"
                  placeholder="Enter tracking number"
                  style={inputStyle}
                  readOnly
                />
              </div>

              <div>
                <label style={labelStyle}>Order Number (optional)</label>
                <input
                  type="text"
                  placeholder="Enter order number"
                  style={inputStyle}
                  readOnly
                />
              </div>

              <div>
                <button type="button" style={buttonStyle}>
                  {settings.button_text || 'Track Shipment'}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  }

  /* ------------------------------------------------------------------ */
  /*  Render                                                             */
  /* ------------------------------------------------------------------ */
  return (
    <div className="grid gap-6 lg:grid-cols-2">
      {/* Left Column */}
      <div className="space-y-6">
        {/* Customize Design */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Palette className="h-5 w-5" />
                Customize Design
              </CardTitle>
              <CardDescription>
                Fine-tune every aspect of your addon appearance
              </CardDescription>
            </div>
            <Button variant="outline" size="sm" onClick={resetCustomization}>
              <RotateCcw className="h-3 w-3 mr-1" />
              Reset
            </Button>
          </CardHeader>
          <CardContent className="space-y-0">
            {/* Quick Start Presets */}
            <div className="flex items-center gap-2 pb-3">
              <span className="text-sm text-muted-foreground">Quick start:</span>
              {quickStartPresets.map(preset => (
                <Button
                  key={preset.id}
                  variant="outline"
                  size="sm"
                  className="h-7 px-2.5 text-xs gap-1.5"
                  onClick={() => applyPreset(preset.id)}
                >
                  <span
                    className="w-3 h-3 rounded-full border"
                    style={{ backgroundColor: preset.color, borderColor: preset.color }}
                  />
                  {preset.label}
                </Button>
              ))}
            </div>

            {/* Form Content — Free */}
            <Collapsible open={expandedSections.content} onOpenChange={() => toggleSection('content')}>
              <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                Form Content
                <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.content ? 'rotate-180' : ''}`} />
              </CollapsibleTrigger>
              <CollapsibleContent className="space-y-4 pt-2 pb-4">
                <div className="space-y-2">
                  <Label htmlFor="form_title" className="text-sm">Form Title</Label>
                  <Input
                    id="form_title"
                    value={settings.form_title}
                    onChange={(e) => updateSetting('form_title', e.target.value)}
                    placeholder="Track Your Order"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="form_description" className="text-sm">Form Description</Label>
                  <Textarea
                    id="form_description"
                    value={settings.form_description}
                    onChange={(e) => updateSetting('form_description', e.target.value)}
                    placeholder="Enter your tracking number below..."
                    rows={3}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="button_text" className="text-sm">Button Text</Label>
                  <Input
                    id="button_text"
                    value={settings.button_text}
                    onChange={(e) => updateSetting('button_text', e.target.value)}
                    placeholder="Track Shipment"
                  />
                </div>
              </CollapsibleContent>
            </Collapsible>

            {/* Colors — Free */}
            <Collapsible open={expandedSections.colors} onOpenChange={() => toggleSection('colors')}>
              <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                Colors
                <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.colors ? 'rotate-180' : ''}`} />
              </CollapsibleTrigger>
              <CollapsibleContent className="space-y-3 pt-2 pb-4">
                <div className="grid grid-cols-2 gap-3">
                  <GlobalColorPicker label="Form Background" value={c.formBackground} onChange={v => updateC('formBackground', v)} globalTokenId="background" />
                  <GlobalColorPicker label="Form Border" value={c.formBorderColor} onChange={v => updateC('formBorderColor', v)} globalTokenId="border" />
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <GlobalColorPicker label="Title Color" value={c.titleColor} onChange={v => updateC('titleColor', v)} globalTokenId="text" />
                  <GlobalColorPicker label="Description Color" value={c.descriptionColor} onChange={v => updateC('descriptionColor', v)} />
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <GlobalColorPicker label="Label Color" value={c.labelColor} onChange={v => updateC('labelColor', v)} globalTokenId="text" />
                  <GlobalColorPicker label="Input Text Color" value={c.inputTextColor} onChange={v => updateC('inputTextColor', v)} globalTokenId="text" />
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <GlobalColorPicker label="Input Background" value={c.inputBackground} onChange={v => updateC('inputBackground', v)} globalTokenId="background" />
                  <GlobalColorPicker label="Input Border" value={c.inputBorderColor} onChange={v => updateC('inputBorderColor', v)} globalTokenId="border" />
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <GlobalColorPicker label="Input Focus Border" value={c.inputFocusBorderColor} onChange={v => updateC('inputFocusBorderColor', v)} globalTokenId="primary" />
                  <GlobalColorPicker label="Button Background" value={c.buttonBackground} onChange={v => updateC('buttonBackground', v)} globalTokenId="primary" />
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <GlobalColorPicker label="Button Text" value={c.buttonTextColor} onChange={v => updateC('buttonTextColor', v)} />
                  <GlobalColorPicker label="Button Hover" value={c.buttonHoverBackground} onChange={v => updateC('buttonHoverBackground', v)} />
                </div>
              </CollapsibleContent>
            </Collapsible>

            {/* Upgrade nudge for Free users */}
            {!isPro && (
              <p className="text-sm text-muted-foreground py-4 border-t">
                For full customization control including typography, spacing, borders,
                and more, upgrade to Swift Commerce Pro.
              </p>
            )}

            {/* Typography — Pro only */}
            {isPro && (
              <Collapsible open={expandedSections.typography} onOpenChange={() => toggleSection('typography')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <span>Typography</span>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.typography ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pt-2 pb-4">
                  <GlobalTypographyPicker
                    label="Font Family"
                    value={c.fontFamily || 'inherit'}
                    onChange={(value) => updateC('fontFamily', value)}
                    globalTokenId="body"
                    featureDefault="inherit"
                  />

                  <div className="space-y-2">
                    <Label className="text-sm text-muted-foreground">Title</Label>
                    <div className="space-y-2">
                      <NumberStepper label="Size" value={c.titleFontSize} onChange={v => updateC('titleFontSize', v)} min={14} max={36} />
                      <div className="flex items-center justify-between gap-2">
                        <Label className="text-sm whitespace-nowrap">Weight</Label>
                        <Select value={c.titleFontWeight} onValueChange={v => updateC('titleFontWeight', v)}>
                          <SelectTrigger className="h-8 w-[140px] text-sm"><SelectValue /></SelectTrigger>
                          <SelectContent>
                            <SelectItem value="400">Normal</SelectItem>
                            <SelectItem value="500">Medium</SelectItem>
                            <SelectItem value="600">Semi-bold</SelectItem>
                            <SelectItem value="700">Bold</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label className="text-sm text-muted-foreground">Description</Label>
                    <NumberStepper label="Size" value={c.descriptionFontSize} onChange={v => updateC('descriptionFontSize', v)} min={10} max={20} />
                  </div>

                  <div className="space-y-2">
                    <Label className="text-sm text-muted-foreground">Labels</Label>
                    <div className="space-y-2">
                      <NumberStepper label="Size" value={c.labelFontSize} onChange={v => updateC('labelFontSize', v)} min={10} max={20} />
                      <div className="flex items-center justify-between gap-2">
                        <Label className="text-sm whitespace-nowrap">Weight</Label>
                        <Select value={c.labelFontWeight} onValueChange={v => updateC('labelFontWeight', v)}>
                          <SelectTrigger className="h-8 w-[140px] text-sm"><SelectValue /></SelectTrigger>
                          <SelectContent>
                            <SelectItem value="400">Normal</SelectItem>
                            <SelectItem value="500">Medium</SelectItem>
                            <SelectItem value="600">Semi-bold</SelectItem>
                            <SelectItem value="700">Bold</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label className="text-sm text-muted-foreground">Input</Label>
                    <NumberStepper label="Size" value={c.inputFontSize} onChange={v => updateC('inputFontSize', v)} min={12} max={20} />
                  </div>

                  <div className="space-y-2">
                    <Label className="text-sm text-muted-foreground">Button</Label>
                    <div className="space-y-2">
                      <NumberStepper label="Size" value={c.buttonFontSize} onChange={v => updateC('buttonFontSize', v)} min={12} max={22} />
                      <div className="flex items-center justify-between gap-2">
                        <Label className="text-sm whitespace-nowrap">Weight</Label>
                        <Select value={c.buttonFontWeight} onValueChange={v => updateC('buttonFontWeight', v)}>
                          <SelectTrigger className="h-8 w-[140px] text-sm"><SelectValue /></SelectTrigger>
                          <SelectContent>
                            <SelectItem value="400">Normal</SelectItem>
                            <SelectItem value="500">Medium</SelectItem>
                            <SelectItem value="600">Semi-bold</SelectItem>
                            <SelectItem value="700">Bold</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  </div>
                </CollapsibleContent>
              </Collapsible>
            )}

            {/* Spacing & Dimensions — Pro only */}
            {isPro && (
              <Collapsible open={expandedSections.spacing} onOpenChange={() => toggleSection('spacing')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <span>Spacing & Dimensions</span>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.spacing ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-3 pt-2 pb-4">
                  <NumberStepper label="Form Border Radius" value={c.formBorderRadius} onChange={v => updateC('formBorderRadius', v)} min={0} max={32} />
                  <NumberStepper label="Form Padding" value={c.formPadding} onChange={v => updateC('formPadding', v)} min={8} max={64} step={2} />
                  <NumberStepper label="Field Spacing" value={c.fieldSpacing} onChange={v => updateC('fieldSpacing', v)} min={8} max={40} step={2} />
                  <NumberStepper label="Input Border Radius" value={c.inputBorderRadius} onChange={v => updateC('inputBorderRadius', v)} min={0} max={20} />
                  <NumberStepper label="Input Padding" value={c.inputPadding} onChange={v => updateC('inputPadding', v)} min={6} max={24} step={2} />
                  <NumberStepper label="Button Border Radius" value={c.buttonBorderRadius} onChange={v => updateC('buttonBorderRadius', v)} min={0} max={24} />
                  <NumberStepper label="Button Padding" value={c.buttonPadding} onChange={v => updateC('buttonPadding', v)} min={6} max={24} step={2} />
                  <NumberStepper label="Form Max Width" value={c.formMaxWidth} onChange={v => updateC('formMaxWidth', v)} min={300} max={800} step={10} />
                </CollapsibleContent>
              </Collapsible>
            )}

            {/* Layout — Pro only */}
            {isPro && (
              <Collapsible open={expandedSections.layout} onOpenChange={() => toggleSection('layout')}>
                <CollapsibleTrigger className="flex w-full items-center justify-between py-3 text-sm font-medium hover:text-primary border-t">
                  <span>Layout</span>
                  <div className="flex items-center gap-2">
                    <ProIndicator size="sm" />
                    <ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.layout ? 'rotate-180' : ''}`} />
                  </div>
                </CollapsibleTrigger>
                <CollapsibleContent className="space-y-4 pt-2 pb-4">
                  <div className="space-y-2">
                    <Label className="text-sm">Form Alignment</Label>
                    <SegmentedControl
                      value={c.formAlignment}
                      onChange={(v) => updateC('formAlignment', v)}
                      options={[
                        { value: 'left', label: 'Left' },
                        { value: 'center', label: 'Center' },
                        { value: 'right', label: 'Right' },
                      ]}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-sm">Title Alignment</Label>
                    <SegmentedControl
                      value={c.titleAlignment}
                      onChange={(v) => updateC('titleAlignment', v)}
                      options={[
                        { value: 'left', label: 'Left' },
                        { value: 'center', label: 'Center' },
                        { value: 'right', label: 'Right' },
                      ]}
                    />
                  </div>
                </CollapsibleContent>
              </Collapsible>
            )}
          </CardContent>
        </Card>

        {/* Shortcode Reference */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Code className="h-5 w-5" />
              Shortcode
            </CardTitle>
            <CardDescription>
              Use this shortcode to display the tracking form on any page
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="p-4 bg-muted rounded-lg font-mono text-sm">
                [swift_commerce_tracking_form]
              </div>
              <div className="text-sm text-muted-foreground">
                <p className="font-medium text-foreground mb-2">Available attributes:</p>
                <ul className="space-y-1">
                  <li><code className="bg-muted px-1 rounded">show_order_field="yes"</code> - Show/hide order number field (yes/no)</li>
                  <li><code className="bg-muted px-1 rounded">show_email_field="yes"</code> - Show/hide email field (yes/no)</li>
                  <li><code className="bg-muted px-1 rounded">button_text="Track"</code> - Custom button text</li>
                </ul>
              </div>
              <div className="p-4 bg-muted rounded-lg font-mono text-sm">
                [swift_commerce_tracking_form show_order_field="no" button_text="Find My Package"]
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Right Column — Sticky Preview */}
      <LivePreview
        title="Live Preview"
        description="Real-time preview of your tracking form"
        stickyTop={100}
        minHeight={400}
        showPattern={true}
        headerActions={
          <Button variant="outline" size="sm" onClick={resetCustomization} className="h-8">
            <RotateCcw className="h-3 w-3 mr-1.5" />
            Reset
          </Button>
        }
      >
        {renderLivePreview()}
      </LivePreview>
    </div>
  )
}
