'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 } from 'lucide-react'

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

  const { data: award, isLoading } = trpc.specialAward.get.useQuery({ id: awardId })
  const updateAward = trpc.specialAward.update.useMutation()

  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')

  // 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))
    }
  }, [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,
      })
      toast.success('Award updated')
      router.push(`/admin/awards/${awardId}`)
    } catch (error) {
      toast.error(
        error instanceof Error ? error.message : 'Failed to update award'
      )
    }
  }

  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>

      <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>
  )
}
