'use client'

import { useState } 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 { toast } from 'sonner'
import { ArrowLeft, Save, Loader2 } from 'lucide-react'

export default function CreateAwardPage() {
  const router = useRouter()
  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 [programId, setProgramId] = useState('')

  const { data: programs } = trpc.program.list.useQuery()
  const createAward = trpc.specialAward.create.useMutation()

  const handleSubmit = async () => {
    if (!name.trim() || !programId) return
    try {
      const award = await createAward.mutateAsync({
        programId,
        name: name.trim(),
        description: description.trim() || undefined,
        criteriaText: criteriaText.trim() || undefined,
        useAiEligibility,
        scoringMode,
        maxRankedPicks:
          scoringMode === 'RANKED' ? parseInt(maxRankedPicks) : undefined,
      })
      toast.success('Award created')
      router.push(`/admin/awards/${award.id}`)
    } catch (error) {
      toast.error(
        error instanceof Error ? error.message : 'Failed to create award'
      )
    }
  }

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

      <div>
        <h1 className="text-2xl font-semibold tracking-tight">
          Create Special Award
        </h1>
        <p className="text-muted-foreground">
          Define a new award with eligibility criteria and voting rules
        </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="program">Edition</Label>
            <Select value={programId} onValueChange={setProgramId}>
              <SelectTrigger id="program">
                <SelectValue placeholder="Select an edition" />
              </SelectTrigger>
              <SelectContent>
                {programs?.map((p) => (
                  <SelectItem key={p.id} value={p.id}>
                    {p.year} Edition
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <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">Cancel</Link>
        </Button>
        <Button
          onClick={handleSubmit}
          disabled={createAward.isPending || !name.trim() || !programId}
        >
          {createAward.isPending ? (
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          ) : (
            <Save className="mr-2 h-4 w-4" />
          )}
          Create Award
        </Button>
      </div>
    </div>
  )
}
