'use client'

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 { Textarea } from '@/components/ui/textarea'
import { Slider } from '@/components/ui/slider'

type FilteringConfigProps = {
  config: Record<string, unknown>
  onChange: (config: Record<string, unknown>) => void
}

export function FilteringConfig({ config, onChange }: FilteringConfigProps) {
  const update = (key: string, value: unknown) => {
    onChange({ ...config, [key]: value })
  }

  const aiEnabled = (config.aiScreeningEnabled as boolean) ?? true
  const thresholds = (config.aiConfidenceThresholds as { high: number; medium: number; low: number }) ?? {
    high: 0.85,
    medium: 0.6,
    low: 0.4,
  }

  const updateThreshold = (key: 'high' | 'medium' | 'low', value: number) => {
    update('aiConfidenceThresholds', { ...thresholds, [key]: value })
  }

  return (
    <div className="space-y-6">
      {/* AI Screening Section */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">AI Screening</CardTitle>
          <CardDescription>
            AI analyzes each project against your criteria and assigns confidence scores.
            Projects above the high threshold auto-pass, below low auto-reject, and between are flagged for manual review.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-5">
          <div className="flex items-center justify-between">
            <div>
              <Label htmlFor="aiScreeningEnabled">Enable AI Screening</Label>
              <p className="text-xs text-muted-foreground">Use AI to pre-screen applications</p>
            </div>
            <Switch
              id="aiScreeningEnabled"
              checked={aiEnabled}
              onCheckedChange={(v) => update('aiScreeningEnabled', v)}
            />
          </div>

          {aiEnabled && (
            <div className="pl-6 border-l-2 border-muted space-y-4">
              <div className="space-y-2">
                <Label htmlFor="aiCriteriaText">Screening Criteria</Label>
                <p className="text-xs text-muted-foreground">
                  Describe what makes a project eligible. The AI uses this text to evaluate each submission.
                  Be specific about requirements, disqualifiers, and what constitutes a strong application.
                </p>
                <Textarea
                  id="aiCriteriaText"
                  rows={6}
                  placeholder="e.g., Projects must address ocean conservation directly. They should have a clear implementation plan, measurable impact metrics, and a team with relevant expertise. Disqualify projects focused solely on freshwater or landlocked environments..."
                  value={(config.aiCriteriaText as string) ?? ''}
                  onChange={(e) => update('aiCriteriaText', e.target.value)}
                />
              </div>

              <div className="space-y-4 rounded-lg border p-4">
                <Label className="text-sm font-medium">Confidence Thresholds</Label>
                <p className="text-xs text-muted-foreground">
                  Set the AI confidence boundaries. Projects scoring above &quot;High&quot; auto-pass,
                  below &quot;Low&quot; auto-reject, and everything between gets flagged for manual review.
                </p>

                <div className="space-y-4">
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <Label className="text-xs text-emerald-600">High (auto-pass above)</Label>
                      <span className="text-xs font-mono font-medium">{thresholds.high.toFixed(2)}</span>
                    </div>
                    <Slider
                      min={0}
                      max={1}
                      step={0.05}
                      value={[thresholds.high]}
                      onValueChange={([v]) => updateThreshold('high', v)}
                      className="[&_[role=slider]]:bg-emerald-500"
                    />
                  </div>

                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <Label className="text-xs text-amber-600">Medium (review threshold)</Label>
                      <span className="text-xs font-mono font-medium">{thresholds.medium.toFixed(2)}</span>
                    </div>
                    <Slider
                      min={0}
                      max={1}
                      step={0.05}
                      value={[thresholds.medium]}
                      onValueChange={([v]) => updateThreshold('medium', v)}
                      className="[&_[role=slider]]:bg-amber-500"
                    />
                  </div>

                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <Label className="text-xs text-red-600">Low (auto-reject below)</Label>
                      <span className="text-xs font-mono font-medium">{thresholds.low.toFixed(2)}</span>
                    </div>
                    <Slider
                      min={0}
                      max={1}
                      step={0.05}
                      value={[thresholds.low]}
                      onValueChange={([v]) => updateThreshold('low', v)}
                      className="[&_[role=slider]]:bg-red-500"
                    />
                  </div>
                </div>
              </div>

              <div className="flex items-center justify-between">
                <div>
                  <Label htmlFor="autoAdvanceEligible">Auto-Advance Eligible</Label>
                  <p className="text-xs text-muted-foreground">
                    Automatically advance projects that score above the high threshold
                  </p>
                </div>
                <Switch
                  id="autoAdvanceEligible"
                  checked={(config.autoAdvanceEligible as boolean) ?? false}
                  onCheckedChange={(v) => update('autoAdvanceEligible', v)}
                />
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Manual Review & Detection */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Review Settings</CardTitle>
          <CardDescription>Manual review and quality checks</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <Label htmlFor="manualReviewEnabled">Manual Review</Label>
              <p className="text-xs text-muted-foreground">Enable admin manual review of flagged projects</p>
            </div>
            <Switch
              id="manualReviewEnabled"
              checked={(config.manualReviewEnabled as boolean) ?? true}
              onCheckedChange={(v) => update('manualReviewEnabled', v)}
            />
          </div>

          <div className="flex items-center justify-between">
            <div>
              <Label htmlFor="duplicateDetectionEnabled">Duplicate Detection</Label>
              <p className="text-xs text-muted-foreground">Flag potential duplicate submissions</p>
            </div>
            <Switch
              id="duplicateDetectionEnabled"
              checked={(config.duplicateDetectionEnabled as boolean) ?? true}
              onCheckedChange={(v) => update('duplicateDetectionEnabled', v)}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="batchSize">Processing Batch Size</Label>
            <p className="text-xs text-muted-foreground">Number of projects processed per AI batch</p>
            <Input
              id="batchSize"
              type="number"
              min={1}
              max={100}
              className="w-32"
              value={(config.batchSize as number) ?? 20}
              onChange={(e) => update('batchSize', parseInt(e.target.value, 10) || 20)}
            />
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
