/**
 * Conditional Logic Tab
 * 
 * Top-level Pro tab that provides an overview of all conditional logic rules
 * configured across checkout fields. This is a dashboard/overview — individual
 * rules are configured per-field in the field edit dialog.
 */

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Switch } from "@/components/ui/switch"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import {
  Zap,
  ArrowRight,
  Pencil,
  Info,
} from "lucide-react"
import {
  CheckoutField,
  conditionalOperators,
} from "../../config"

interface ConditionalLogicTabProps {
  fields: CheckoutField[]
  onEditField: (field: CheckoutField) => void
  updateField: (id: string, updates: Partial<CheckoutField>) => void
}

export function ConditionalLogicTab({
  fields,
  onEditField,
  updateField,
}: ConditionalLogicTabProps) {
  // Fields that have conditional logic configured (regardless of enabled state)
  const fieldsWithCL = fields.filter(
    (f) => f.conditionalLogic && f.conditionalLogic.rules.length > 0
  )

  // Fields with active (enabled) conditional logic
  const activeFields = fieldsWithCL.filter((f) => f.conditionalLogic?.enabled)

  const toggleCLEnabled = (field: CheckoutField) => {
    if (!field.conditionalLogic) return
    updateField(field.id, {
      conditionalLogic: {
        ...field.conditionalLogic,
        enabled: !field.conditionalLogic.enabled,
      },
    })
  }

  const getOperatorLabel = (operator: string) => {
    return (
      conditionalOperators.find((o) => o.value === operator)?.label || operator
    )
  }

  const getFieldLabel = (fieldKey: string) => {
    const field = fields.find((f) => f.key === fieldKey)
    return field?.label || fieldKey
  }

  return (
    <div className="space-y-6">
      {/* Overview Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Total Rules</CardDescription>
            <CardTitle className="text-2xl">{fieldsWithCL.length}</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-xs text-muted-foreground">
              Fields with conditional logic configured
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Active</CardDescription>
            <CardTitle className="text-2xl text-green-600">
              {activeFields.length}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-xs text-muted-foreground">
              Fields with conditional logic enabled
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Inactive</CardDescription>
            <CardTitle className="text-2xl text-muted-foreground">
              {fieldsWithCL.length - activeFields.length}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-xs text-muted-foreground">
              Fields with logic configured but disabled
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Rules Table */}
      {fieldsWithCL.length > 0 ? (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Zap className="h-5 w-5 text-amber-500" />
              Conditional Logic Rules
            </CardTitle>
            <CardDescription>
              Overview of all conditional logic rules. Click edit to configure
              individual rules per field.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Field</TableHead>
                  <TableHead>Action</TableHead>
                  <TableHead>Rules</TableHead>
                  <TableHead className="text-center">Active</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {fieldsWithCL.map((field) => {
                  const cl = field.conditionalLogic!
                  return (
                    <TableRow key={field.id}>
                      <TableCell>
                        <div>
                          <span className="font-medium">{field.label}</span>
                          <span className="text-xs text-muted-foreground ml-2">
                            ({field.section})
                          </span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant={
                            cl.action === 'show' || cl.action === 'enable'
                              ? 'default'
                              : 'secondary'
                          }
                        >
                          {cl.action}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <div className="space-y-1">
                          {cl.rules.slice(0, 2).map((rule, i) => (
                            <div
                              key={rule.id || i}
                              className="flex items-center gap-1 text-xs"
                            >
                              <span className="font-medium text-muted-foreground">
                                {getFieldLabel(rule.field)}
                              </span>
                              <ArrowRight className="h-3 w-3 text-muted-foreground" />
                              <span>{getOperatorLabel(rule.operator)}</span>
                              {rule.value && (
                                <span className="font-mono text-xs bg-muted px-1 rounded">
                                  {rule.value}
                                </span>
                              )}
                            </div>
                          ))}
                          {cl.rules.length > 2 && (
                            <span className="text-xs text-muted-foreground">
                              +{cl.rules.length - 2} more rule
                              {cl.rules.length - 2 > 1 ? 's' : ''}
                            </span>
                          )}
                          <Badge
                            variant="outline"
                            className="text-[10px] px-1 py-0"
                          >
                            {cl.logic === 'all' ? 'ALL match' : 'ANY match'}
                          </Badge>
                        </div>
                      </TableCell>
                      <TableCell className="text-center">
                        <Switch
                          checked={cl.enabled}
                          onCheckedChange={() => toggleCLEnabled(field)}
                        />
                      </TableCell>
                      <TableCell className="text-right">
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button
                                size="icon"
                                variant="ghost"
                                onClick={() => onEditField(field)}
                              >
                                <Pencil className="h-4 w-4" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>
                              Edit field & conditional logic
                            </TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </TableCell>
                    </TableRow>
                  )
                })}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      ) : (
        // Empty State
        <Card>
          <CardContent className="py-12">
            <div className="text-center space-y-4">
              <div className="mx-auto w-12 h-12 rounded-full bg-amber-50 flex items-center justify-center">
                <Zap className="h-6 w-6 text-amber-500" />
              </div>
              <div className="space-y-2">
                <h3 className="font-semibold text-lg">
                  No Conditional Logic Configured
                </h3>
                <p className="text-muted-foreground max-w-md mx-auto">
                  Conditional logic lets you show, hide, enable, or disable
                  checkout fields based on other field values. To get started,
                  edit a field and configure rules in the Conditional Logic tab.
                </p>
              </div>
              <div className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
                <Info className="h-4 w-4" />
                <span>
                  Go to Field Editor → Edit a field → Conditional Logic tab
                </span>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
