'use client'

import { use, useState, useEffect } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
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 { Textarea } from '@/components/ui/textarea'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { Skeleton } from '@/components/ui/skeleton'
import { toast } from 'sonner'
import { ArrowLeft, Save, Loader2, Plus, X, Info } from 'lucide-react'
import { Badge } from '@/components/ui/badge'

type AutoTagRule = {
  id: string
  field: 'competitionCategory' | 'country' | 'geographicZone' | 'tags' | 'oceanIssue'
  operator: 'equals' | 'contains' | 'in'
  value: string
}

export default function EditAwardPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id: awardId } = use(params)
  const router = useRouter()

  const utils = trpc.useUtils()
  const { data: award, isLoading } = trpc.specialAward.get.useQuery({ id: awardId })

  // Fetch competition rounds for source round selector
  const competitionId = award?.competitionId
  const { data: competition } = trpc.competition.getById.useQuery(
    { id: competitionId! },
    { enabled: !!competitionId }
  )

  const updateAward = trpc.specialAward.update.useMutation({
    onSuccess: () => {
      utils.specialAward.get.invalidate({ id: awardId })
      utils.specialAward.list.invalidate()
    },
  })

  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [criteriaText, setCriteriaText] = useState('')
  const [scoringMode, setScoringMode] = useState<'PICK_WINNER' | 'RANKED' | 'SCORED'>('PICK_WINNER')
  const [useAiEligibility, setUseAiEligibility] = useState(true)
  const [maxRankedPicks, setMaxRankedPicks] = useState('3')
  const [votingStartAt, setVotingStartAt] = useState('')
  const [votingEndAt, setVotingEndAt] = useState('')
  const [evaluationRoundId, setEvaluationRoundId] = useState('')
  const [eligibilityMode, setEligibilityMode] = useState<'STAY_IN_MAIN' | 'SEPARATE_POOL'>('STAY_IN_MAIN')
  const [autoTagRules, setAutoTagRules] = useState<AutoTagRule[]>([])

  // Helper to format date for datetime-local input
  const formatDateForInput = (date: Date | string | null | undefined): string => {
    if (!date) return ''
    const d = new Date(date)
    // Format: YYYY-MM-DDTHH:mm
    return d.toISOString().slice(0, 16)
  }

  // Load existing values when award data arrives
  useEffect(() => {
    if (award) {
      setName(award.name)
      setDescription(award.description || '')
      setCriteriaText(award.criteriaText || '')
      setScoringMode(award.scoringMode as 'PICK_WINNER' | 'RANKED' | 'SCORED')
      setUseAiEligibility(award.useAiEligibility)
      setMaxRankedPicks(String(award.maxRankedPicks || 3))
      setVotingStartAt(formatDateForInput(award.votingStartAt))
      setVotingEndAt(formatDateForInput(award.votingEndAt))
      setEvaluationRoundId(award.evaluationRoundId || '')
      setEligibilityMode(award.eligibilityMode as 'STAY_IN_MAIN' | 'SEPARATE_POOL')

      // Parse autoTagRulesJson
      if (award.autoTagRulesJson && typeof award.autoTagRulesJson === 'object') {
        const rules = award.autoTagRulesJson as { rules?: AutoTagRule[] }
        setAutoTagRules(rules.rules || [])
      } else {
        setAutoTagRules([])
      }
    }
  }, [award])

  const handleSubmit = async () => {
    if (!name.trim()) return
    try {
      await updateAward.mutateAsync({
        id: awardId,
        name: name.trim(),
        description: description.trim() || undefined,
        criteriaText: criteriaText.trim() || undefined,
        useAiEligibility,
        scoringMode,
        maxRankedPicks: scoringMode === 'RANKED' ? parseInt(maxRankedPicks) : undefined,
        votingStartAt: votingStartAt ? new Date(votingStartAt) : undefined,
        votingEndAt: votingEndAt ? new Date(votingEndAt) : undefined,
        evaluationRoundId: evaluationRoundId || undefined,
        eligibilityMode,
        autoTagRulesJson: autoTagRules.length > 0 ? { rules: autoTagRules } : undefined,
      })
      toast.success('Award updated')
      router.push(`/admin/awards/${awardId}`)
    } catch (error) {
      toast.error(
        error instanceof Error ? error.message : 'Failed to update award'
      )
    }
  }

  const addRule = () => {
    setAutoTagRules([
      ...autoTagRules,
      {
        id: `rule-${Date.now()}`,
        field: 'competitionCategory',
        operator: 'equals',
        value: '',
      },
    ])
  }

  const removeRule = (id: string) => {
    setAutoTagRules(autoTagRules.filter((r) => r.id !== id))
  }

  const updateRule = (id: string, updates: Partial<AutoTagRule>) => {
    setAutoTagRules(
      autoTagRules.map((r) => (r.id === id ? { ...r, ...updates } : r))
    )
  }

  if (isLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-9 w-48" />
        <Skeleton className="h-[400px] w-full" />
      </div>
    )
  }

  if (!award) return null

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

      <div>
        <h1 className="text-2xl font-semibold tracking-tight">
          Edit Award
        </h1>
        <p className="text-muted-foreground">
          Update award settings and eligibility criteria
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Award Details</CardTitle>
          <CardDescription>
            Configure the award name, criteria, and scoring mode
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="name">Award Name</Label>
            <Input
              id="name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="e.g., Mediterranean Entrepreneurship Award"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="description">Description</Label>
            <Textarea
              id="description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Brief description of this award"
              rows={3}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="criteria">Eligibility Criteria</Label>
            <Textarea
              id="criteria"
              value={criteriaText}
              onChange={(e) => setCriteriaText(e.target.value)}
              placeholder="Describe the criteria in plain language. AI will interpret this to evaluate project eligibility."
              rows={4}
            />
            <p className="text-xs text-muted-foreground">
              This text will be used by AI to determine which projects are
              eligible for this award.
            </p>
          </div>

          <div className="flex items-center justify-between rounded-lg border p-4">
            <div className="space-y-0.5">
              <Label htmlFor="ai-toggle">AI Eligibility</Label>
              <p className="text-xs text-muted-foreground">
                Use AI to automatically evaluate project eligibility based on the criteria above.
                Turn off for awards decided by feeling or manual selection.
              </p>
            </div>
            <Switch
              id="ai-toggle"
              checked={useAiEligibility}
              onCheckedChange={setUseAiEligibility}
            />
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="scoring">Scoring Mode</Label>
              <Select
                value={scoringMode}
                onValueChange={(v) =>
                  setScoringMode(v as 'PICK_WINNER' | 'RANKED' | 'SCORED')
                }
              >
                <SelectTrigger id="scoring">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="PICK_WINNER">
                    Pick Winner — Each juror picks 1
                  </SelectItem>
                  <SelectItem value="RANKED">
                    Ranked — Each juror ranks top N
                  </SelectItem>
                  <SelectItem value="SCORED">
                    Scored — Use evaluation form
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>

            {scoringMode === 'RANKED' && (
              <div className="space-y-2">
                <Label htmlFor="maxPicks">Max Ranked Picks</Label>
                <Input
                  id="maxPicks"
                  type="number"
                  min="1"
                  max="20"
                  value={maxRankedPicks}
                  onChange={(e) => setMaxRankedPicks(e.target.value)}
                />
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Source Round & Eligibility */}
      <Card>
        <CardHeader>
          <CardTitle>Source Round & Pool</CardTitle>
          <CardDescription>
            Define which round feeds projects into this award and how they interact with the main competition
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="sourceRound">Source Round</Label>
              <Select
                value={evaluationRoundId || 'none'}
                onValueChange={(v) => setEvaluationRoundId(v === 'none' ? '' : v)}
              >
                <SelectTrigger id="sourceRound">
                  <SelectValue placeholder="Select round..." />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">No source round</SelectItem>
                  {competition?.rounds
                    ?.sort((a, b) => a.sortOrder - b.sortOrder)
                    .map((round) => (
                      <SelectItem key={round.id} value={round.id}>
                        {round.name} ({round.roundType})
                      </SelectItem>
                    ))}
                </SelectContent>
              </Select>
              <p className="text-xs text-muted-foreground">
                Projects from this round will be considered for award eligibility
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="eligibilityMode">Eligibility Mode</Label>
              <Select
                value={eligibilityMode}
                onValueChange={(v) =>
                  setEligibilityMode(v as 'STAY_IN_MAIN' | 'SEPARATE_POOL')
                }
              >
                <SelectTrigger id="eligibilityMode">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="STAY_IN_MAIN">
                    Stay in Main — Projects remain in competition
                  </SelectItem>
                  <SelectItem value="SEPARATE_POOL">
                    Separate Pool — Projects exit to award track
                  </SelectItem>
                </SelectContent>
              </Select>
              <p className="text-xs text-muted-foreground">
                Whether award-eligible projects continue in the main competition or move to a separate track
              </p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Auto-Tag Rules */}
      <Card>
        <CardHeader>
          <div className="flex items-start justify-between">
            <div>
              <CardTitle>Auto-Tag Rules</CardTitle>
              <CardDescription>
                Deterministic eligibility rules based on project metadata
              </CardDescription>
            </div>
            <Button variant="outline" size="sm" onClick={addRule}>
              <Plus className="mr-2 h-4 w-4" />
              Add Rule
            </Button>
          </div>
        </CardHeader>
        <CardContent className="space-y-3">
          {autoTagRules.length === 0 ? (
            <div className="flex items-start gap-2 rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
              <Info className="h-4 w-4 mt-0.5 shrink-0" />
              <p>
                No rules defined. Add rules to automatically filter projects based on category, location, tags, or ocean issues.
                Rules work together with the source round setting.
              </p>
            </div>
          ) : (
            <div className="space-y-3">
              {autoTagRules.map((rule, index) => (
                <div
                  key={rule.id}
                  className="flex items-start gap-3 rounded-lg border p-3"
                >
                  <div className="flex-1 grid gap-3 sm:grid-cols-3">
                    <div className="space-y-1.5">
                      <Label className="text-xs">Field</Label>
                      <Select
                        value={rule.field}
                        onValueChange={(v) =>
                          updateRule(rule.id, {
                            field: v as AutoTagRule['field'],
                          })
                        }
                      >
                        <SelectTrigger className="h-9">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="competitionCategory">
                            Competition Category
                          </SelectItem>
                          <SelectItem value="country">Country</SelectItem>
                          <SelectItem value="geographicZone">
                            Geographic Zone
                          </SelectItem>
                          <SelectItem value="tags">Tags</SelectItem>
                          <SelectItem value="oceanIssue">Ocean Issue</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-1.5">
                      <Label className="text-xs">Operator</Label>
                      <Select
                        value={rule.operator}
                        onValueChange={(v) =>
                          updateRule(rule.id, {
                            operator: v as AutoTagRule['operator'],
                          })
                        }
                      >
                        <SelectTrigger className="h-9">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="equals">Equals</SelectItem>
                          <SelectItem value="contains">Contains</SelectItem>
                          <SelectItem value="in">In (comma-separated)</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-1.5">
                      <Label className="text-xs">Value</Label>
                      <Input
                        className="h-9"
                        value={rule.value}
                        onChange={(e) =>
                          updateRule(rule.id, { value: e.target.value })
                        }
                        placeholder={
                          rule.operator === 'in'
                            ? 'value1,value2,value3'
                            : 'Enter value...'
                        }
                      />
                    </div>
                  </div>

                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-9 w-9 shrink-0"
                    onClick={() => removeRule(rule.id)}
                  >
                    <X className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          )}

          {autoTagRules.length > 0 && (
            <div className="flex items-start gap-2 rounded-lg bg-muted p-3 text-xs text-muted-foreground">
              <Info className="h-3 w-3 mt-0.5 shrink-0" />
              <p>
                <strong>How it works:</strong> Filter from{' '}
                <Badge variant="outline" className="mx-1">
                  {evaluationRoundId
                    ? competition?.rounds?.find((r) => r.id === evaluationRoundId)
                        ?.name || 'Selected Round'
                    : 'All Projects'}
                </Badge>
                , where ALL rules match (AND logic). Projects matching these deterministic rules will be marked eligible.
              </p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Voting Window Card */}
      <Card>
        <CardHeader>
          <CardTitle>Voting Window</CardTitle>
          <CardDescription>
            Set the time period during which jurors can submit their votes
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="votingStart">Voting Opens</Label>
              <Input
                id="votingStart"
                type="datetime-local"
                value={votingStartAt}
                onChange={(e) => setVotingStartAt(e.target.value)}
              />
              <p className="text-xs text-muted-foreground">
                When jurors can start voting (leave empty to set when opening voting)
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="votingEnd">Voting Closes</Label>
              <Input
                id="votingEnd"
                type="datetime-local"
                value={votingEndAt}
                onChange={(e) => setVotingEndAt(e.target.value)}
              />
              <p className="text-xs text-muted-foreground">
                Deadline for juror votes
              </p>
            </div>
          </div>
        </CardContent>
      </Card>

      <div className="flex justify-end gap-4">
        <Button variant="outline" asChild>
          <Link href={`/admin/awards/${awardId}`}>Cancel</Link>
        </Button>
        <Button
          onClick={handleSubmit}
          disabled={updateAward.isPending || !name.trim()}
        >
          {updateAward.isPending ? (
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          ) : (
            <Save className="mr-2 h-4 w-4" />
          )}
          Save Changes
        </Button>
      </div>
    </div>
  )
}
