/**
 * Registration Form Settings Tab
 * 
 * Global settings for the registration form editor
 */

import { useState, useEffect } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Button } from "@/components/ui/button"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Separator } from "@/components/ui/separator"
import {
  Settings,
  Monitor,
  Layout,
  FileUp,
  Zap,
  ShieldCheck,
  UserCog,
  Plus,
  Trash2,
} from "lucide-react"
import { usePro } from "@/contexts/pro-context"
import { ProIndicator } from "@/components/pro/pro-indicator"
import {
  RegistrationFormSettings,
  LayoutStyle,
  FieldSpacing,
  LabelPosition,
  RequiredIndicatorPosition,
  RedirectType,
  RoleAssignmentRule,
  RoleAssignmentOperator,
  RegistrationField,
} from "../../config"

interface Page {
  id: number
  title: string
}

interface SettingsTabProps {
  settings: RegistrationFormSettings
  fields: RegistrationField[]
  onUpdateSettings: (updates: Partial<RegistrationFormSettings>) => void
}

interface WPRole {
  key: string
  name: string
}

export function SettingsTab({ settings, fields, onUpdateSettings }: SettingsTabProps) {
  const { isPro } = usePro()
  const [pages, setPages] = useState<Page[]>([])
  const [loadingPages, setLoadingPages] = useState(false)
  const [roles, setRoles] = useState<WPRole[]>([])
  const [loadingRoles, setLoadingRoles] = useState(false)

  // Load pages for redirect selection
  useEffect(() => {
    const loadPages = async () => {
      setLoadingPages(true)
      try {
        const apiUrl = window.swiftCommerceData?.apiUrl || '/wp-json/swift-commerce/v1'
        const response = await fetch(`${apiUrl}/pages`, {
          headers: {
            'X-WP-Nonce': window.swiftCommerceData?.restNonce || '',
          },
          credentials: 'same-origin',
        })
        if (response.ok) {
          const data = await response.json()
          setPages(data.pages || [])
        }
      } catch (error) {
        console.error('Failed to load pages:', error)
      } finally {
        setLoadingPages(false)
      }
    }
    loadPages()
  }, [])

  // Load roles for role assignment
  useEffect(() => {
    if (!isPro) return
    const loadRoles = async () => {
      setLoadingRoles(true)
      try {
        const apiUrl = window.swiftCommerceData?.apiUrl || '/wp-json/swift-commerce/v1'
        const response = await fetch(`${apiUrl}/registration-form/roles`, {
          headers: {
            'X-WP-Nonce': window.swiftCommerceData?.restNonce || '',
          },
          credentials: 'same-origin',
        })
        if (response.ok) {
          const data = await response.json()
          setRoles(Array.isArray(data) ? data : [])
        }
      } catch (error) {
        console.error('Failed to load roles:', error)
      } finally {
        setLoadingRoles(false)
      }
    }
    loadRoles()
  }, [isPro])

  // Custom fields available for role rules (non-core, non-content fields)
  const assignableFields = fields.filter(
    (f) => !f.isCore && f.enabled && !['heading', 'paragraph', 'divider', 'file'].includes(f.type)
  )

  const addRoleRule = () => {
    const newRule: RoleAssignmentRule = {
      id: `rule_${Date.now()}`,
      fieldKey: assignableFields[0]?.key || '',
      operator: 'is_not_empty',
      value: '',
      role: roles[0]?.key || 'subscriber',
    }
    onUpdateSettings({
      roleAssignment: {
        ...settings.roleAssignment,
        rules: [...settings.roleAssignment.rules, newRule],
      },
    })
  }

  const updateRoleRule = (ruleId: string, updates: Partial<RoleAssignmentRule>) => {
    onUpdateSettings({
      roleAssignment: {
        ...settings.roleAssignment,
        rules: settings.roleAssignment.rules.map((r) =>
          r.id === ruleId ? { ...r, ...updates } : r
        ),
      },
    })
  }

  const deleteRoleRule = (ruleId: string) => {
    onUpdateSettings({
      roleAssignment: {
        ...settings.roleAssignment,
        rules: settings.roleAssignment.rules.filter((r) => r.id !== ruleId),
      },
    })
  }

  return (
    <div className="grid grid-cols-2 gap-6">
      {/* Left Column */}
      <div className="space-y-6">
        {/* Context Settings */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Monitor className="h-5 w-5" />
            Form Context
          </CardTitle>
          <CardDescription>
            Choose where the custom registration form should be applied.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <Label htmlFor="applyToWordPress">WordPress Registration</Label>
              <p className="text-sm text-muted-foreground">
                Apply to wp-login.php?action=register
              </p>
            </div>
            <Switch
              id="applyToWordPress"
              checked={settings.applyToWordPress}
              onCheckedChange={(checked) => onUpdateSettings({ applyToWordPress: checked })}
            />
          </div>
          
          <Separator />
          
          {isPro && (
          <div className="flex items-center justify-between">
            <div>
              <Label htmlFor="applyToWooCommerce">WooCommerce My Account</Label>
              <ProIndicator size="sm" />
              <p className="text-sm text-muted-foreground">
                Apply to WooCommerce My Account registration form
              </p>
            </div>
            <Switch
              id="applyToWooCommerce"
              checked={settings.applyToWooCommerce}
              onCheckedChange={(checked) => onUpdateSettings({ applyToWooCommerce: checked })}
            />
          </div>
          )}
          
          {isPro && (
          <>
          <Separator />
          
          <div className="flex items-center justify-between">
            <div>
              <Label htmlFor="applyToCheckout">Checkout Registration</Label>
              <ProIndicator size="sm" />
              <p className="text-sm text-muted-foreground">
                Apply custom fields during checkout registration
              </p>
            </div>
            <Switch
              id="applyToCheckout"
              checked={settings.applyToCheckout}
              onCheckedChange={(checked) => onUpdateSettings({ applyToCheckout: checked })}
            />
          </div>
          </>
          )}
          
          {isPro && (
          <>
          <Separator />
          
          <div className="flex items-center justify-between">
            <div>
              <Label htmlFor="applyToMyAccount">My Account Edit</Label>
              <ProIndicator size="sm" />
              <p className="text-sm text-muted-foreground">
                Show custom fields in My Account details page
              </p>
            </div>
            <Switch
              id="applyToMyAccount"
              checked={settings.applyToMyAccount}
              onCheckedChange={(checked) => onUpdateSettings({ applyToMyAccount: checked })}
            />
          </div>
          </>
          )}
        </CardContent>
      </Card>

      {/* Display Settings */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Settings className="h-5 w-5" />
            Display Settings
          </CardTitle>
          <CardDescription>
            Configure how fields are displayed in the registration form.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <Label htmlFor="showLabels">Show Field Labels</Label>
            <Switch
              id="showLabels"
              checked={settings.showLabels}
              onCheckedChange={(checked) => onUpdateSettings({ showLabels: checked })}
            />
          </div>
          
          <div className="flex items-center justify-between">
            <Label htmlFor="showPlaceholders">Show Placeholders</Label>
            <Switch
              id="showPlaceholders"
              checked={settings.showPlaceholders}
              onCheckedChange={(checked) => onUpdateSettings({ showPlaceholders: checked })}
            />
          </div>
          
          <div className="flex items-center justify-between">
            <Label htmlFor="showDescriptions">Show Field Descriptions</Label>
            <Switch
              id="showDescriptions"
              checked={settings.showDescriptions}
              onCheckedChange={(checked) => onUpdateSettings({ showDescriptions: checked })}
            />
          </div>
          
          <Separator />
          
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="requiredIndicator">Required Indicator</Label>
              <Input
                id="requiredIndicator"
                value={settings.requiredIndicator}
                onChange={(e) => onUpdateSettings({ requiredIndicator: e.target.value })}
                placeholder="*"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="requiredIndicatorPosition">Position</Label>
              <Select
                value={settings.requiredIndicatorPosition}
                onValueChange={(value: RequiredIndicatorPosition) => 
                  onUpdateSettings({ requiredIndicatorPosition: value })
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="before">Before Label</SelectItem>
                  <SelectItem value="after">After Label</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Layout Settings */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Layout className="h-5 w-5" />
            Layout Settings
          </CardTitle>
          <CardDescription>
            Customize the layout and appearance of the registration form.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="layoutStyle">Layout Style</Label>
              <Select
                value={settings.layoutStyle}
                onValueChange={(value: LayoutStyle) => onUpdateSettings({ layoutStyle: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="stacked">Stacked (Vertical)</SelectItem>
                  <SelectItem value="inline">Inline (Horizontal)</SelectItem>
                  <SelectItem value="grid">Grid</SelectItem>
                </SelectContent>
              </Select>
            </div>
            
            <div className="space-y-2">
              <Label htmlFor="columnsCount">Grid Columns</Label>
              <Select
                value={settings.columnsCount.toString()}
                onValueChange={(value) => onUpdateSettings({ columnsCount: parseInt(value) })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">1 Column</SelectItem>
                  <SelectItem value="2">2 Columns</SelectItem>
                  <SelectItem value="3">3 Columns</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="fieldSpacing">Field Spacing</Label>
              <Select
                value={settings.fieldSpacing}
                onValueChange={(value: FieldSpacing) => onUpdateSettings({ fieldSpacing: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="compact">Compact</SelectItem>
                  <SelectItem value="normal">Normal</SelectItem>
                  <SelectItem value="relaxed">Relaxed</SelectItem>
                </SelectContent>
              </Select>
            </div>
            
            <div className="space-y-2">
              <Label htmlFor="labelPosition">Label Position</Label>
              <Select
                value={settings.labelPosition}
                onValueChange={(value: LabelPosition) => onUpdateSettings({ labelPosition: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="above">Above Field</SelectItem>
                  <SelectItem value="inline">Inline (Side)</SelectItem>
                  <SelectItem value="floating">Floating Label</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>
      </div>

      {/* Right Column */}
      <div className="space-y-6">
      {/* Behavior Settings - Pro Only */}
      {isPro && (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Zap className="h-5 w-5" />
            Behavior Settings
            <ProIndicator size="sm" />
          </CardTitle>
          <CardDescription>
            Configure post-registration behavior and features.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label>Redirect After Registration</Label>
            <Select
              value={settings.redirectType || 'default'}
              onValueChange={(value: RedirectType) => onUpdateSettings({ redirectType: value })}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select redirect type" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="default">Default (No redirect)</SelectItem>
                <SelectItem value="url">Custom URL</SelectItem>
                <SelectItem value="page">WordPress Page</SelectItem>
              </SelectContent>
            </Select>
          </div>
          
          {settings.redirectType === 'url' && (
            <div className="space-y-2 pl-4 border-l-2 border-muted">
              <Label htmlFor="redirectAfterRegister">Redirect URL</Label>
              <Input
                id="redirectAfterRegister"
                value={settings.redirectAfterRegister}
                onChange={(e) => onUpdateSettings({ redirectAfterRegister: e.target.value })}
                placeholder="https://example.com/welcome"
              />
            </div>
          )}
          
          {settings.redirectType === 'page' && (
            <div className="space-y-2 pl-4 border-l-2 border-muted">
              <Label>Select Page</Label>
              <Select
                value={settings.redirectPageId?.toString() || '0'}
                onValueChange={(value) => onUpdateSettings({ redirectPageId: parseInt(value) })}
                disabled={loadingPages}
              >
                <SelectTrigger>
                  <SelectValue placeholder={loadingPages ? "Loading pages..." : "Select a page"} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="0">-- Select a page --</SelectItem>
                  {pages.map((page) => (
                    <SelectItem key={page.id} value={page.id.toString()}>
                      {page.title}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}
          
          <Separator />
          
          <div className="flex items-center justify-between">
            <div>
              <Label htmlFor="autoLogin">Auto Login After Registration</Label>
              <p className="text-sm text-muted-foreground">
                Automatically log in users after successful registration
              </p>
            </div>
            <Switch
              id="autoLogin"
              checked={settings.autoLogin}
              onCheckedChange={(checked) => onUpdateSettings({ autoLogin: checked })}
            />
          </div>
        </CardContent>
      </Card>
      )}

      {/* Advanced Settings - Pro Only */}
      {isPro && (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FileUp className="h-5 w-5" />
            Advanced Settings
            <ProIndicator size="sm" />
          </CardTitle>
          <CardDescription>
            Configure file upload settings for registration forms.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <Label htmlFor="enableFileUploads">Enable File Uploads</Label>
              <p className="text-sm text-muted-foreground">
                Allow file upload fields in registration form
              </p>
            </div>
            <Switch
              id="enableFileUploads"
              checked={settings.enableFileUploads}
              onCheckedChange={(checked) => onUpdateSettings({ enableFileUploads: checked })}
            />
          </div>
          
          {settings.enableFileUploads && (
            <div className="grid grid-cols-2 gap-4 pl-4 border-l-2 border-muted">
              <div className="space-y-2">
                <Label htmlFor="maxFileSize">Max File Size (MB)</Label>
                <Input
                  id="maxFileSize"
                  type="number"
                  value={settings.maxFileSize}
                  onChange={(e) => onUpdateSettings({ maxFileSize: parseInt(e.target.value) || 5 })}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="allowedFileTypes">Allowed File Types</Label>
                <Input
                  id="allowedFileTypes"
                  value={settings.allowedFileTypes}
                  onChange={(e) => onUpdateSettings({ allowedFileTypes: e.target.value })}
                  placeholder="jpg,jpeg,png,pdf"
                />
              </div>
            </div>
          )}
        </CardContent>
      </Card>
      )}

      {/* CAPTCHA Protection - Pro Only */}
      {isPro && (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <ShieldCheck className="h-5 w-5" />
            CAPTCHA Protection
            <ProIndicator size="sm" />
          </CardTitle>
          <CardDescription>
            Add CAPTCHA verification to registration forms using your configured reCAPTCHA, Turnstile, or hCaptcha provider.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <Label htmlFor="enableCaptcha">Enable CAPTCHA on Registration</Label>
              <p className="text-sm text-muted-foreground">
                Display a CAPTCHA challenge on all active registration forms
              </p>
            </div>
            <Switch
              id="enableCaptcha"
              checked={settings.enableCaptcha}
              onCheckedChange={(checked) => onUpdateSettings({ enableCaptcha: checked })}
            />
          </div>

          {settings.enableCaptcha && (
            <p className="text-xs text-muted-foreground pl-4 border-l-2 border-muted">
              The CAPTCHA provider is configured in the reCAPTCHA feature settings. Make sure you have a provider set up with valid API keys.
            </p>
          )}
        </CardContent>
      </Card>
      )}

      {/* Role Assignment - Pro Only */}
      {isPro && (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <UserCog className="h-5 w-5" />
            Role Assignment
            <ProIndicator size="sm" />
          </CardTitle>
          <CardDescription>
            Automatically assign user roles based on registration form field values. Rules are evaluated top-to-bottom — first match wins.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <Label htmlFor="enableRoleAssignment">Enable Role Assignment</Label>
              <p className="text-sm text-muted-foreground">
                Assign roles based on form data (e.g., Tax ID → Wholesale)
              </p>
            </div>
            <Switch
              id="enableRoleAssignment"
              checked={settings.roleAssignment.enabled}
              onCheckedChange={(checked) =>
                onUpdateSettings({
                  roleAssignment: { ...settings.roleAssignment, enabled: checked },
                })
              }
            />
          </div>

          {settings.roleAssignment.enabled && (
            <div className="space-y-4 pt-4 border-t">
              {/* Default role */}
              <div className="space-y-2">
                <Label>Default Role (when no rule matches)</Label>
                <Select
                  value={settings.roleAssignment.defaultRole || '__wp_default__'}
                  onValueChange={(value) =>
                    onUpdateSettings({
                      roleAssignment: {
                        ...settings.roleAssignment,
                        defaultRole: value === '__wp_default__' ? '' : value,
                      },
                    })
                  }
                  disabled={loadingRoles}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Use WordPress default" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="__wp_default__">Use WordPress default</SelectItem>
                    {roles.map((role) => (
                      <SelectItem key={role.key} value={role.key}>
                        {role.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <p className="text-xs text-muted-foreground">
                  Leave empty to use the WordPress default role setting.
                </p>
              </div>

              <Separator />

              {/* Rules list */}
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <Label className="text-sm font-medium">Assignment Rules</Label>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={addRoleRule}
                    disabled={assignableFields.length === 0}
                  >
                    <Plus className="h-4 w-4 mr-1" />
                    Add Rule
                  </Button>
                </div>

                {assignableFields.length === 0 && (
                  <p className="text-sm text-muted-foreground">
                    Add custom fields to the form first, then create rules here.
                  </p>
                )}

                {settings.roleAssignment.rules.map((rule) => (
                  <div
                    key={rule.id}
                    className="grid grid-cols-[1fr_auto] gap-2 p-3 border rounded-md bg-muted/30"
                  >
                    <div className="grid grid-cols-2 gap-2">
                      {/* Field */}
                      <div className="space-y-1">
                        <Label className="text-xs text-muted-foreground">If field</Label>
                        <Select
                          value={rule.fieldKey}
                          onValueChange={(v) => updateRoleRule(rule.id, { fieldKey: v })}
                        >
                          <SelectTrigger className="h-8 text-xs">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {assignableFields.map((f) => (
                              <SelectItem key={f.key} value={f.key}>
                                {f.label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Operator */}
                      <div className="space-y-1">
                        <Label className="text-xs text-muted-foreground">Condition</Label>
                        <Select
                          value={rule.operator}
                          onValueChange={(v: RoleAssignmentOperator) =>
                            updateRoleRule(rule.id, { operator: v })
                          }
                        >
                          <SelectTrigger className="h-8 text-xs">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="equals">Equals</SelectItem>
                            <SelectItem value="not_equals">Does not equal</SelectItem>
                            <SelectItem value="contains">Contains</SelectItem>
                            <SelectItem value="not_contains">Does not contain</SelectItem>
                            <SelectItem value="is_empty">Is empty</SelectItem>
                            <SelectItem value="is_not_empty">Is not empty</SelectItem>
                            <SelectItem value="is_checked">Is checked</SelectItem>
                            <SelectItem value="is_not_checked">Is not checked</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Value (hidden for empty/checked operators) */}
                      {!['is_empty', 'is_not_empty', 'is_checked', 'is_not_checked'].includes(
                        rule.operator
                      ) && (
                        <div className="space-y-1">
                          <Label className="text-xs text-muted-foreground">Value</Label>
                          <Input
                            className="h-8 text-xs"
                            value={rule.value}
                            onChange={(e) => updateRoleRule(rule.id, { value: e.target.value })}
                            placeholder="Match value"
                          />
                        </div>
                      )}

                      {/* Target role */}
                      <div className="space-y-1">
                        <Label className="text-xs text-muted-foreground">Assign role</Label>
                        <Select
                          value={rule.role}
                          onValueChange={(v) => updateRoleRule(rule.id, { role: v })}
                          disabled={loadingRoles}
                        >
                          <SelectTrigger className="h-8 text-xs">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {roles.map((role) => (
                              <SelectItem key={role.key} value={role.key}>
                                {role.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>

                    {/* Delete */}
                    <div className="flex items-end">
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="h-8 w-8 text-muted-foreground hover:text-destructive"
                        onClick={() => deleteRoleRule(rule.id)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </CardContent>
      </Card>
      )}

      </div>
    </div>
  )
}
