'use client';

import { use, useState } from 'react';
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 { Checkbox } from '@/components/ui/checkbox';
import { ArrowLeft } from 'lucide-react';
import { toast } from 'sonner';
import type { Route } from 'next';

export default function NewAwardPage({ params: paramsPromise }: { params: Promise<{ competitionId: string }> }) {
  const params = use(paramsPromise);
  const router = useRouter();
  const utils = trpc.useUtils();

  const [formData, setFormData] = useState({
    name: '',
    description: '',
    useAiEligibility: false,
    scoringMode: 'PICK_WINNER' as 'PICK_WINNER' | 'RANKED' | 'SCORED'
  });

  const { data: competition } = trpc.competition.getById.useQuery({
    id: params.competitionId
  });

  const { data: juryGroups } = trpc.juryGroup.list.useQuery({
    competitionId: params.competitionId
  });

  const createMutation = trpc.specialAward.create.useMutation({
    onSuccess: () => {
      utils.specialAward.list.invalidate();
      toast.success('Award created successfully');
      router.push(`/admin/competitions/${params.competitionId}/awards` as Route);
    },
    onError: (err) => {
      toast.error(err.message);
    }
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData.name.trim()) {
      toast.error('Award name is required');
      return;
    }

    if (!competition?.programId) {
      toast.error('Competition data not loaded');
      return;
    }

    createMutation.mutate({
      programId: competition.programId,
      name: formData.name.trim(),
      description: formData.description.trim() || undefined,
      scoringMode: formData.scoringMode,
      useAiEligibility: formData.useAiEligibility
    });
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button
          variant="ghost"
          size="icon"
          onClick={() => router.push(`/admin/competitions/${params.competitionId}/awards` as Route)}
        >
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <div>
          <h1 className="text-3xl font-bold">Create Special Award</h1>
          <p className="text-muted-foreground">Define a new award for this competition</p>
        </div>
      </div>

      <form onSubmit={handleSubmit}>
        <Card>
          <CardHeader>
            <CardTitle>Award Details</CardTitle>
            <CardDescription>Configure the award properties and eligibility</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-2">
              <Label htmlFor="name">Award Name *</Label>
              <Input
                id="name"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="e.g., Best Innovation Award"
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="description">Description</Label>
              <Textarea
                id="description"
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="Describe the award criteria and purpose"
                rows={3}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="scoringMode">Scoring Mode</Label>
              <Select
                value={formData.scoringMode}
                onValueChange={(value) =>
                  setFormData({ ...formData, scoringMode: value as 'PICK_WINNER' | 'RANKED' | 'SCORED' })
                }
              >
                <SelectTrigger id="scoringMode">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="PICK_WINNER">Pick Winner</SelectItem>
                  <SelectItem value="RANKED">Ranked</SelectItem>
                  <SelectItem value="SCORED">Scored</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="flex items-center space-x-2">
              <Checkbox
                id="useAiEligibility"
                checked={formData.useAiEligibility}
                onCheckedChange={(checked) =>
                  setFormData({ ...formData, useAiEligibility: checked as boolean })
                }
              />
              <Label htmlFor="useAiEligibility" className="font-normal">
                Use AI-based eligibility assessment
              </Label>
            </div>

            <div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
              <Button
                type="button"
                variant="outline"
                onClick={() => router.push(`/admin/competitions/${params.competitionId}/awards` as Route)}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={createMutation.isPending}>
                {createMutation.isPending ? 'Creating...' : 'Create Award'}
              </Button>
            </div>
          </CardContent>
        </Card>
      </form>
    </div>
  );
}
