'use client'

import { use, useState } from 'react'
import Link from 'next/link'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Switch } from '@/components/ui/switch'
import { Skeleton } from '@/components/ui/skeleton'
import { Textarea } from '@/components/ui/textarea'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import { toast } from 'sonner'
import {
  ArrowLeft,
  Plus,
  Trash2,
  GripVertical,
  Loader2,
  FileCheck,
  Brain,
  Filter,
} from 'lucide-react'

type RuleType = 'FIELD_BASED' | 'DOCUMENT_CHECK' | 'AI_SCREENING'

const RULE_TYPE_LABELS: Record<RuleType, string> = {
  FIELD_BASED: 'Field-Based',
  DOCUMENT_CHECK: 'Document Check',
  AI_SCREENING: 'AI Screening',
}

const RULE_TYPE_ICONS: Record<RuleType, React.ReactNode> = {
  FIELD_BASED: <Filter className="h-4 w-4" />,
  DOCUMENT_CHECK: <FileCheck className="h-4 w-4" />,
  AI_SCREENING: <Brain className="h-4 w-4" />,
}

const FIELD_OPTIONS = [
  { value: 'competitionCategory', label: 'Competition Category' },
  { value: 'foundedAt', label: 'Founded Date' },
  { value: 'country', label: 'Country' },
  { value: 'geographicZone', label: 'Geographic Zone' },
  { value: 'tags', label: 'Tags' },
  { value: 'oceanIssue', label: 'Ocean Issue' },
]

const OPERATOR_OPTIONS = [
  { value: 'equals', label: 'Equals' },
  { value: 'not_equals', label: 'Not Equals' },
  { value: 'contains', label: 'Contains' },
  { value: 'in', label: 'In (list)' },
  { value: 'not_in', label: 'Not In (list)' },
  { value: 'is_empty', label: 'Is Empty' },
  { value: 'older_than_years', label: 'Older Than (years)' },
  { value: 'newer_than_years', label: 'Newer Than (years)' },
]

export default function FilteringRulesPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id: roundId } = use(params)

  const { data: rules, isLoading, refetch } =
    trpc.filtering.getRules.useQuery({ roundId })
  const createRule = trpc.filtering.createRule.useMutation()
  const updateRule = trpc.filtering.updateRule.useMutation()
  const deleteRule = trpc.filtering.deleteRule.useMutation()

  const [showCreateDialog, setShowCreateDialog] = useState(false)
  const [newRuleName, setNewRuleName] = useState('')
  const [newRuleType, setNewRuleType] = useState<RuleType>('FIELD_BASED')

  // Field-based config state
  const [conditionField, setConditionField] = useState('competitionCategory')
  const [conditionOperator, setConditionOperator] = useState('equals')
  const [conditionValue, setConditionValue] = useState('')
  const [conditionLogic, setConditionLogic] = useState<'AND' | 'OR'>('AND')
  const [conditionAction, setConditionAction] = useState<'PASS' | 'REJECT' | 'FLAG'>('REJECT')

  // Document check config state
  const [minFileCount, setMinFileCount] = useState('1')
  const [docAction, setDocAction] = useState<'PASS' | 'REJECT' | 'FLAG'>('REJECT')

  // AI screening config state
  const [criteriaText, setCriteriaText] = useState('')
  const [aiBatchSize, setAiBatchSize] = useState('20')
  const [aiParallelBatches, setAiParallelBatches] = useState('1')

  const handleCreateRule = async () => {
    if (!newRuleName.trim()) return

    let configJson: Record<string, unknown> = {}

    if (newRuleType === 'FIELD_BASED') {
      configJson = {
        conditions: [
          {
            field: conditionField,
            operator: conditionOperator,
            value: conditionOperator === 'in' || conditionOperator === 'not_in'
              ? conditionValue.split(',').map((v) => v.trim())
              : conditionOperator === 'older_than_years' ||
                  conditionOperator === 'newer_than_years' ||
                  conditionOperator === 'greater_than' ||
                  conditionOperator === 'less_than'
                ? Number(conditionValue)
                : conditionValue,
          },
        ],
        logic: conditionLogic,
        action: conditionAction,
      }
    } else if (newRuleType === 'DOCUMENT_CHECK') {
      configJson = {
        minFileCount: parseInt(minFileCount) || 1,
        action: docAction,
      }
    } else if (newRuleType === 'AI_SCREENING') {
      configJson = {
        criteriaText,
        action: 'FLAG',
        batchSize: parseInt(aiBatchSize) || 20,
        parallelBatches: parseInt(aiParallelBatches) || 1,
      }
    }

    try {
      await createRule.mutateAsync({
        roundId,
        name: newRuleName.trim(),
        ruleType: newRuleType,
        configJson,
        priority: (rules?.length || 0) + 1,
      })
      toast.success('Rule created')
      setShowCreateDialog(false)
      resetForm()
      refetch()
    } catch (error) {
      toast.error(
        error instanceof Error ? error.message : 'Failed to create rule'
      )
    }
  }

  const handleToggleActive = async (ruleId: string, isActive: boolean) => {
    try {
      await updateRule.mutateAsync({ id: ruleId, isActive })
      refetch()
    } catch {
      toast.error('Failed to update rule')
    }
  }

  const handleDeleteRule = async (ruleId: string) => {
    try {
      await deleteRule.mutateAsync({ id: ruleId })
      toast.success('Rule deleted')
      refetch()
    } catch {
      toast.error('Failed to delete rule')
    }
  }

  const resetForm = () => {
    setNewRuleName('')
    setNewRuleType('FIELD_BASED')
    setConditionField('competitionCategory')
    setConditionOperator('equals')
    setConditionValue('')
    setConditionLogic('AND')
    setConditionAction('REJECT')
    setMinFileCount('1')
    setDocAction('REJECT')
    setCriteriaText('')
    setAiBatchSize('20')
    setAiParallelBatches('1')
  }

  if (isLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-9 w-48" />
        <div className="space-y-4">
          {[...Array(3)].map((_, i) => (
            <Skeleton key={i} className="h-24 w-full" />
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" asChild className="-ml-4">
          <Link href={`/admin/rounds/${roundId}/filtering`}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Filtering
          </Link>
        </Button>
      </div>

      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">
            Filtering Rules
          </h1>
          <p className="text-muted-foreground">
            Rules are evaluated in order of priority
          </p>
        </div>
        <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              Add Rule
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-lg">
            <DialogHeader>
              <DialogTitle>Create Filtering Rule</DialogTitle>
              <DialogDescription>
                Define conditions that projects must meet
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4">
              <div className="space-y-2">
                <Label>Rule Name</Label>
                <Input
                  value={newRuleName}
                  onChange={(e) => setNewRuleName(e.target.value)}
                  placeholder="e.g., Startup age check"
                />
              </div>
              <div className="space-y-2">
                <Label>Rule Type</Label>
                <Select
                  value={newRuleType}
                  onValueChange={(v) => setNewRuleType(v as RuleType)}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="FIELD_BASED">Field-Based</SelectItem>
                    <SelectItem value="DOCUMENT_CHECK">
                      Document Check
                    </SelectItem>
                    <SelectItem value="AI_SCREENING">AI Screening</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* Field-Based Config */}
              {newRuleType === 'FIELD_BASED' && (
                <>
                  <div className="grid gap-4 sm:grid-cols-2">
                    <div className="space-y-2">
                      <Label>Field</Label>
                      <Select
                        value={conditionField}
                        onValueChange={setConditionField}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {FIELD_OPTIONS.map((f) => (
                            <SelectItem key={f.value} value={f.value}>
                              {f.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                      <Label>Operator</Label>
                      <Select
                        value={conditionOperator}
                        onValueChange={setConditionOperator}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {OPERATOR_OPTIONS.map((o) => (
                            <SelectItem key={o.value} value={o.value}>
                              {o.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  {conditionOperator !== 'is_empty' && (
                    <div className="space-y-2">
                      <Label>Value</Label>
                      <Input
                        value={conditionValue}
                        onChange={(e) => setConditionValue(e.target.value)}
                        placeholder={
                          conditionOperator === 'in' ||
                          conditionOperator === 'not_in'
                            ? 'Comma-separated values'
                            : 'Value'
                        }
                      />
                    </div>
                  )}
                  <div className="grid gap-4 sm:grid-cols-2">
                    <div className="space-y-2">
                      <Label>Logic</Label>
                      <Select
                        value={conditionLogic}
                        onValueChange={(v) =>
                          setConditionLogic(v as 'AND' | 'OR')
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="AND">AND</SelectItem>
                          <SelectItem value="OR">OR</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                      <Label>Action</Label>
                      <Select
                        value={conditionAction}
                        onValueChange={(v) =>
                          setConditionAction(v as 'PASS' | 'REJECT' | 'FLAG')
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="PASS">Pass</SelectItem>
                          <SelectItem value="REJECT">Reject</SelectItem>
                          <SelectItem value="FLAG">Flag</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </>
              )}

              {/* Document Check Config */}
              {newRuleType === 'DOCUMENT_CHECK' && (
                <>
                  <div className="space-y-2">
                    <Label>Minimum File Count</Label>
                    <Input
                      type="number"
                      min="1"
                      value={minFileCount}
                      onChange={(e) => setMinFileCount(e.target.value)}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Action if not met</Label>
                    <Select
                      value={docAction}
                      onValueChange={(v) =>
                        setDocAction(v as 'PASS' | 'REJECT' | 'FLAG')
                      }
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="REJECT">Reject</SelectItem>
                        <SelectItem value="FLAG">Flag</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </>
              )}

              {/* AI Screening Config */}
              {newRuleType === 'AI_SCREENING' && (
                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label>Screening Criteria</Label>
                    <Textarea
                      value={criteriaText}
                      onChange={(e) => setCriteriaText(e.target.value)}
                      placeholder="Describe the criteria for AI to evaluate projects against..."
                      rows={4}
                    />
                    <p className="text-xs text-muted-foreground">
                      AI screening always flags projects for human review, never
                      auto-rejects.
                    </p>
                  </div>

                  <div className="border-t pt-4">
                    <Label className="text-sm font-medium">Performance Settings</Label>
                    <p className="text-xs text-muted-foreground mb-3">
                      Adjust batch settings to balance speed vs. cost
                    </p>
                    <div className="grid gap-4 sm:grid-cols-2">
                      <div className="space-y-2">
                        <Label className="text-xs">Batch Size</Label>
                        <Select value={aiBatchSize} onValueChange={setAiBatchSize}>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="1">1 (Individual)</SelectItem>
                            <SelectItem value="5">5 (Small)</SelectItem>
                            <SelectItem value="10">10 (Medium)</SelectItem>
                            <SelectItem value="20">20 (Default)</SelectItem>
                            <SelectItem value="50">50 (Large)</SelectItem>
                          </SelectContent>
                        </Select>
                        <p className="text-[10px] text-muted-foreground">
                          Projects per API call. Smaller = more parallel potential
                        </p>
                      </div>
                      <div className="space-y-2">
                        <Label className="text-xs">Parallel Requests</Label>
                        <Select value={aiParallelBatches} onValueChange={setAiParallelBatches}>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="1">1 (Sequential)</SelectItem>
                            <SelectItem value="2">2</SelectItem>
                            <SelectItem value="3">3</SelectItem>
                            <SelectItem value="5">5 (Fast)</SelectItem>
                            <SelectItem value="10">10 (Maximum)</SelectItem>
                          </SelectContent>
                        </Select>
                        <p className="text-[10px] text-muted-foreground">
                          Concurrent API calls. Higher = faster but more costly
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => setShowCreateDialog(false)}
              >
                Cancel
              </Button>
              <Button
                onClick={handleCreateRule}
                disabled={
                  createRule.isPending ||
                  !newRuleName.trim() ||
                  (newRuleType === 'AI_SCREENING' && !criteriaText.trim())
                }
              >
                {createRule.isPending && (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                )}
                Create Rule
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      {/* Rules List */}
      {rules && rules.length > 0 ? (
        <div className="space-y-3">
          {rules.map((rule, index) => (
            <Card key={rule.id}>
              <CardContent className="flex items-center gap-4 py-4">
                <div className="flex items-center gap-2 text-muted-foreground">
                  <GripVertical className="h-4 w-4" />
                  <span className="text-sm font-mono w-6 text-center">
                    {index + 1}
                  </span>
                </div>

                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    {RULE_TYPE_ICONS[rule.ruleType as RuleType]}
                    <p className="font-medium">{rule.name}</p>
                    <Badge variant="outline">
                      {RULE_TYPE_LABELS[rule.ruleType as RuleType]}
                    </Badge>
                    {!rule.isActive && (
                      <Badge variant="secondary">Disabled</Badge>
                    )}
                  </div>
                  <p className="text-sm text-muted-foreground mt-1">
                    {rule.ruleType === 'AI_SCREENING'
                      ? (rule.configJson as Record<string, unknown>)
                          ?.criteriaText
                        ? String(
                            (rule.configJson as Record<string, unknown>)
                              .criteriaText
                          ).slice(0, 80) + '...'
                        : 'AI screening rule'
                      : rule.ruleType === 'DOCUMENT_CHECK'
                        ? `Min ${(rule.configJson as Record<string, unknown>)?.minFileCount || 1} file(s)`
                        : `${((rule.configJson as Record<string, unknown>)?.conditions as Array<Record<string, unknown>>)?.length || 0} condition(s)`}
                  </p>
                </div>

                <Switch
                  checked={rule.isActive}
                  onCheckedChange={(checked) =>
                    handleToggleActive(rule.id, checked)
                  }
                />

                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => handleDeleteRule(rule.id)}
                  disabled={deleteRule.isPending}
                  className="text-muted-foreground hover:text-destructive"
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </CardContent>
            </Card>
          ))}
        </div>
      ) : (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <Filter className="h-12 w-12 text-muted-foreground/50" />
            <p className="mt-2 font-medium">No rules configured</p>
            <p className="text-sm text-muted-foreground">
              Add filtering rules to screen projects automatically
            </p>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
