/**
 * Conditional Logic Editor
 * 
 * Per-field rule builder component for configuring conditional logic.
 * This is a Pro-only component rendered inside the field edit dialog.
 */

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Plus,
  Trash2,
  Zap,
  AlertCircle,
} from "lucide-react"
import {
  CheckoutField,
  ConditionalLogic,
  ConditionalRule,
  ConditionalOperator,
  conditionalOperators,
  noValueOperators,
  getOperatorsForFieldType,
  generateRuleId,
  fieldTypeDefinitions,
} from "../config"

interface ConditionalLogicEditorProps {
  field: CheckoutField
  allFields: CheckoutField[]
  conditionalLogic: ConditionalLogic | undefined
  onChange: (cl: ConditionalLogic) => void
}

const defaultConditionalLogic: ConditionalLogic = {
  enabled: false,
  action: 'show',
  logic: 'all',
  rules: [],
}

export function ConditionalLogicEditor({
  field,
  allFields,
  conditionalLogic,
  onChange,
}: ConditionalLogicEditorProps) {
  const cl = conditionalLogic || defaultConditionalLogic

  // Get available trigger fields (all fields except the current one)
  const triggerFields = allFields.filter(
    (f) => f.id !== field.id && f.enabled && f.type !== 'heading' && f.type !== 'paragraph' && f.type !== 'label'
  )

  const updateCL = (updates: Partial<ConditionalLogic>) => {
    onChange({ ...cl, ...updates })
  }

  const addRule = () => {
    const newRule: ConditionalRule = {
      id: generateRuleId(),
      field: triggerFields.length > 0 ? triggerFields[0].key : '',
      operator: 'equals',
      value: '',
    }
    updateCL({ rules: [...cl.rules, newRule] })
  }

  const updateRule = (ruleId: string, updates: Partial<ConditionalRule>) => {
    updateCL({
      rules: cl.rules.map((r) =>
        r.id === ruleId ? { ...r, ...updates } : r
      ),
    })
  }

  const removeRule = (ruleId: string) => {
    updateCL({ rules: cl.rules.filter((r) => r.id !== ruleId) })
  }

  // Get available operators for a trigger field
  const getAvailableOperators = (triggerFieldKey: string) => {
    const triggerField = allFields.find((f) => f.key === triggerFieldKey)
    if (!triggerField) return conditionalOperators
    const allowed = getOperatorsForFieldType(triggerField.type)
    return conditionalOperators.filter((op) => allowed.includes(op.value))
  }

  // Get options for a trigger field (select, radio, checkbox_group)
  const getTriggerFieldOptions = (triggerFieldKey: string) => {
    const triggerField = allFields.find((f) => f.key === triggerFieldKey)
    if (!triggerField || !triggerField.options) return null
    return triggerField.options
  }

  // Check if operator requires a value input
  const isNoValueOperator = (operator: ConditionalOperator) => {
    return noValueOperators.includes(operator)
  }

  // When trigger field changes, reset operator and value
  const handleTriggerFieldChange = (ruleId: string, newFieldKey: string) => {
    const triggerField = allFields.find((f) => f.key === newFieldKey)
    const defaultOp = triggerField?.type === 'checkbox' ? 'checked' : 'equals'
    updateRule(ruleId, { field: newFieldKey, operator: defaultOp, value: '' })
  }

  return (
    <div className="space-y-4">
      {/* Enable Toggle */}
      <div className="flex items-center justify-between p-4 bg-muted/50 rounded-lg">
        <div className="flex items-center gap-2">
          <Zap className="h-4 w-4 text-amber-500" />
          <div>
            <Label className="font-medium">Enable Conditional Logic</Label>
            <p className="text-xs text-muted-foreground">
              Show, hide, enable, or disable this field based on other field values
            </p>
          </div>
        </div>
        <Switch
          checked={cl.enabled}
          onCheckedChange={(enabled) => updateCL({ enabled })}
        />
      </div>

      {cl.enabled && (
        <div className="space-y-4">
          {/* Action & Logic Row */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Action</Label>
              <Select
                value={cl.action}
                onValueChange={(v) =>
                  updateCL({ action: v as ConditionalLogic['action'] })
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="show">Show this field</SelectItem>
                  <SelectItem value="hide">Hide this field</SelectItem>
                  <SelectItem value="enable">Enable this field</SelectItem>
                  <SelectItem value="disable">Disable this field</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Match</Label>
              <Select
                value={cl.logic}
                onValueChange={(v) =>
                  updateCL({ logic: v as ConditionalLogic['logic'] })
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All rules match (AND)</SelectItem>
                  <SelectItem value="any">Any rule matches (OR)</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* Rules */}
          <div className="space-y-2">
            <Label>Rules</Label>

            {triggerFields.length === 0 && (
              <div className="flex items-center gap-2 p-3 text-sm text-amber-700 bg-amber-50 border border-amber-200 rounded-lg">
                <AlertCircle className="h-4 w-4 flex-shrink-0" />
                <span>No other enabled fields available to use as triggers.</span>
              </div>
            )}

            {cl.rules.map((rule, index) => {
              const availableOps = getAvailableOperators(rule.field)
              const triggerOptions = getTriggerFieldOptions(rule.field)
              const showValueInput = !isNoValueOperator(rule.operator)
              const triggerField = allFields.find((f) => f.key === rule.field)
              const triggerFieldDef = triggerField
                ? fieldTypeDefinitions.find((fd) => fd.type === triggerField.type)
                : null

              return (
                <div key={rule.id} className="space-y-2">
                  {index > 0 && (
                    <div className="flex items-center gap-2 py-1">
                      <div className="flex-1 border-t" />
                      <span className="text-xs font-medium text-muted-foreground uppercase">
                        {cl.logic === 'all' ? 'AND' : 'OR'}
                      </span>
                      <div className="flex-1 border-t" />
                    </div>
                  )}

                  <div className="flex items-start gap-2 p-3 bg-muted/30 rounded-lg border">
                    <div className="flex-1 grid grid-cols-1 gap-2">
                      {/* Trigger Field */}
                      <Select
                        value={rule.field}
                        onValueChange={(v) => handleTriggerFieldChange(rule.id, v)}
                      >
                        <SelectTrigger className="w-full">
                          <SelectValue placeholder="Select field..." />
                        </SelectTrigger>
                        <SelectContent>
                          {triggerFields.map((tf) => (
                            <SelectItem key={tf.key} value={tf.key}>
                              {tf.label}{' '}
                              <span className="text-muted-foreground">
                                ({tf.section})
                              </span>
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>

                      <div className="grid grid-cols-2 gap-2">
                        {/* Operator */}
                        <Select
                          value={rule.operator}
                          onValueChange={(v) =>
                            updateRule(rule.id, {
                              operator: v as ConditionalOperator,
                              // Clear value when switching to a no-value operator
                              ...(noValueOperators.includes(v as ConditionalOperator) ? { value: '' } : {}),
                            })
                          }
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {availableOps.map((op) => (
                              <SelectItem key={op.value} value={op.value}>
                                {op.label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>

                        {/* Value Input */}
                        {showValueInput && (
                          <>
                            {triggerOptions && triggerOptions.length > 0 ? (
                              <Select
                                value={rule.value}
                                onValueChange={(v) =>
                                  updateRule(rule.id, { value: v })
                                }
                              >
                                <SelectTrigger>
                                  <SelectValue placeholder="Select value..." />
                                </SelectTrigger>
                                <SelectContent>
                                  {triggerOptions.map((opt) => (
                                    <SelectItem key={opt.value} value={opt.value}>
                                      {opt.label}
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                            ) : (
                              <Input
                                value={rule.value}
                                onChange={(e) =>
                                  updateRule(rule.id, { value: e.target.value })
                                }
                                placeholder={
                                  triggerFieldDef?.type === 'number'
                                    ? 'Enter number...'
                                    : 'Enter value...'
                                }
                                type={triggerFieldDef?.type === 'number' ? 'number' : 'text'}
                              />
                            )}
                          </>
                        )}
                      </div>
                    </div>

                    {/* Remove Rule */}
                    <Button
                      size="icon"
                      variant="ghost"
                      onClick={() => removeRule(rule.id)}
                      className="flex-shrink-0 mt-0.5"
                    >
                      <Trash2 className="h-4 w-4 text-destructive" />
                    </Button>
                  </div>
                </div>
              )
            })}

            {/* Add Rule Button */}
            <Button
              variant="outline"
              size="sm"
              onClick={addRule}
              disabled={triggerFields.length === 0}
              className="w-full mt-2"
            >
              <Plus className="h-4 w-4 mr-1" />
              Add Rule
            </Button>
          </div>

          {/* Validation Warning */}
          {cl.enabled && cl.rules.length === 0 && (
            <div className="flex items-center gap-2 p-3 text-sm text-amber-700 bg-amber-50 border border-amber-200 rounded-lg">
              <AlertCircle className="h-4 w-4 flex-shrink-0" />
              <span>
                Add at least one rule for conditional logic to take effect.
              </span>
            </div>
          )}
        </div>
      )}
    </div>
  )
}
