/**
 * Checkout Field Editor - Settings Tab
 * 
 * Global settings for the checkout field editor
 */

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Input } from "@/components/ui/input"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Button } from "@/components/ui/button"
import { Separator } from "@/components/ui/separator"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { 
  Eye,
  FileCode,
  Upload,
  MapPin,
  Download,
  Upload as UploadIcon,
  Shield,
} from "lucide-react"
import { FieldEditorSettings } from "../../config"
import { usePro } from "@/contexts/pro-context"

interface SettingsTabProps {
  settings: FieldEditorSettings
  updateSettings: <K extends keyof FieldEditorSettings>(key: K, value: FieldEditorSettings[K]) => void
  exportSettings: () => string
  importSettings: (json: string) => boolean
}

export function SettingsTab({
  settings, 
  updateSettings,
  exportSettings,
  importSettings
}: SettingsTabProps) {
  const { isPro } = usePro()

  const handleExport = () => {
    const json = exportSettings()
    const blob = new Blob([json], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = 'checkout-fields-export.json'
    a.click()
    URL.revokeObjectURL(url)
  }

  const handleImport = () => {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = '.json'
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0]
      if (file) {
        const reader = new FileReader()
        reader.onload = (e) => {
          const content = e.target?.result as string
          importSettings(content)
        }
        reader.readAsText(file)
      }
    }
    input.click()
  }

  return (
    <div className="grid gap-6 lg:grid-cols-2">
      {/* Left Column */}
      <div className="space-y-6">
        {/* Display Settings */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Eye className="h-5 w-5" />
              Display Settings
            </CardTitle>
            <CardDescription>
              Control how fields are displayed on the checkout page.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label>Show Field Labels</Label>
              <p className="text-sm text-muted-foreground">
                Display labels above form fields.
              </p>
            </div>
            <Switch
              checked={settings.showFieldLabels}
              onCheckedChange={(v) => updateSettings('showFieldLabels', v)}
            />
          </div>

          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label>Show Placeholders</Label>
              <p className="text-sm text-muted-foreground">
                Display placeholder text inside fields.
              </p>
            </div>
            <Switch
              checked={settings.showPlaceholders}
              onCheckedChange={(v) => updateSettings('showPlaceholders', v)}
            />
          </div>

          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label>Show Field Descriptions</Label>
              <p className="text-sm text-muted-foreground">
                Display help text below fields.
              </p>
            </div>
            <Switch
              checked={settings.showDescriptions}
              onCheckedChange={(v) => updateSettings('showDescriptions', v)}
            />
          </div>

          <Separator />

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Required Field Indicator</Label>
              <Input
                value={settings.requiredIndicator}
                onChange={(e) => updateSettings('requiredIndicator', e.target.value)}
                placeholder="*"
              />
            </div>
            <div className="space-y-2">
              <Label>Indicator Position</Label>
              <Select
                value={settings.requiredIndicatorPosition}
                onValueChange={(v) => updateSettings('requiredIndicatorPosition', v as 'before' | 'after')}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="before">Before label</SelectItem>
                  <SelectItem value="after">After label</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Validation Settings */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Shield className="h-5 w-5" />
            Validation Settings
          </CardTitle>
          <CardDescription>
            Configure how field validation behaves.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label>Validate on Blur</Label>
              <p className="text-sm text-muted-foreground">
                Validate fields when user leaves them.
              </p>
            </div>
            <Switch
              checked={settings.validateOnBlur}
              onCheckedChange={(v) => updateSettings('validateOnBlur', v)}
            />
          </div>

          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label>Validate on Submit</Label>
              <p className="text-sm text-muted-foreground">
                Validate all fields when form is submitted.
              </p>
            </div>
            <Switch
              checked={settings.validateOnSubmit}
              onCheckedChange={(v) => updateSettings('validateOnSubmit', v)}
            />
          </div>

          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label>Show Errors Inline</Label>
              <p className="text-sm text-muted-foreground">
                Display error messages next to fields.
              </p>
            </div>
            <Switch
              checked={settings.showErrorsInline}
              onCheckedChange={(v) => updateSettings('showErrorsInline', v)}
            />
          </div>

          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label>Scroll to First Error</Label>
              <p className="text-sm text-muted-foreground">
                Automatically scroll to the first error on validation.
              </p>
            </div>
            <Switch
              checked={settings.scrollToError}
              onCheckedChange={(v) => updateSettings('scrollToError', v)}
            />
          </div>

          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label>Highlight Error Fields</Label>
              <p className="text-sm text-muted-foreground">
                Add visual highlight to fields with errors.
              </p>
            </div>
            <Switch
              checked={settings.highlightErrorFields}
              onCheckedChange={(v) => updateSettings('highlightErrorFields', v)}
            />
          </div>

          <div className="space-y-2">
            <Label>Error Position</Label>
            <RadioGroup
              value={settings.errorPosition}
              onValueChange={(v) => updateSettings('errorPosition', v as 'above' | 'below')}
              className="flex gap-4"
            >
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="above" id="error-above" />
                <Label htmlFor="error-above" className="font-normal">Above field</Label>
              </div>
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="below" id="error-below" />
                <Label htmlFor="error-below" className="font-normal">Below field</Label>
              </div>
            </RadioGroup>
          </div>
        </CardContent>
      </Card>

        {/* Address Override Settings */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <MapPin className="h-5 w-5" />
              Address Override Settings
            </CardTitle>
            <CardDescription>
              Configure how address fields interact with user profiles.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label>Override Address Fields</Label>
                <p className="text-sm text-muted-foreground">
                  Allow checkout fields to override saved address data.
                </p>
              </div>
              <Switch
                checked={settings.overrideAddressFields}
                onCheckedChange={(v) => updateSettings('overrideAddressFields', v)}
              />
            </div>

            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label>Allow Billing Override</Label>
                <p className="text-sm text-muted-foreground">
                  Users can override their saved billing address.
                </p>
              </div>
              <Switch
                checked={settings.allowBillingOverride}
                onCheckedChange={(v) => updateSettings('allowBillingOverride', v)}
              />
            </div>

            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label>Allow Shipping Override</Label>
                <p className="text-sm text-muted-foreground">
                  Users can override their saved shipping address.
                </p>
              </div>
              <Switch
                checked={settings.allowShippingOverride}
                onCheckedChange={(v) => updateSettings('allowShippingOverride', v)}
              />
            </div>

            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label>Sync Billing & Shipping</Label>
                <p className="text-sm text-muted-foreground">
                  Keep billing and shipping address in sync.
                </p>
              </div>
              <Switch
                checked={settings.syncBillingShipping}
                onCheckedChange={(v) => updateSettings('syncBillingShipping', v)}
              />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Right Column */}
      <div className="space-y-6">
        {/* File Upload Settings - Pro Only */}
      {isPro && (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Upload className="h-5 w-5" />
            File Upload Settings
          </CardTitle>
          <CardDescription>
            Configure file upload behavior for file fields.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="space-y-2">
            <Label>Upload Directory</Label>
            <Input
              value={settings.fileUploadPath}
              onChange={(e) => updateSettings('fileUploadPath', e.target.value)}
              placeholder="checkout-uploads"
            />
            <p className="text-sm text-muted-foreground">
              Files will be stored in wp-content/uploads/{settings.fileUploadPath || 'checkout-uploads'}
            </p>
          </div>

          <div className="space-y-2">
            <Label>Max Total Upload Size (MB)</Label>
            <Input
              type="number"
              value={settings.maxTotalUploadSize}
              onChange={(e) => updateSettings('maxTotalUploadSize', parseInt(e.target.value) || 10)}
              min={1}
              max={100}
            />
            <p className="text-sm text-muted-foreground">
              Maximum total size of all file uploads per checkout.
            </p>
          </div>
        </CardContent>
      </Card>
      )}

      {/* Import/Export */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FileCode className="h-5 w-5" />
            Import & Export
          </CardTitle>
          <CardDescription>
            Backup your checkout field configuration.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap gap-3">
            <Button variant="outline" onClick={handleExport}>
              <Download className="h-4 w-4 mr-2" />
              Export Settings
            </Button>
            <Button variant="outline" onClick={handleImport}>
              <UploadIcon className="h-4 w-4 mr-2" />
              Import Settings
            </Button>
          </div>
        </CardContent>
      </Card>
      </div>
    </div>
  )
}
