'use client'

import { Suspense, use, useState, useEffect } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { trpc } from '@/lib/trpc/client'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
import { Badge } from '@/components/ui/badge'
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import {
  EvaluationFormBuilder,
  type Criterion,
} from '@/components/forms/evaluation-form-builder'
import { RoundTypeSettings } from '@/components/forms/round-type-settings'
import { ArrowLeft, Loader2, AlertCircle, AlertTriangle } from 'lucide-react'
import { DateTimePicker } from '@/components/ui/datetime-picker'

interface PageProps {
  params: Promise<{ id: string }>
}

const updateRoundSchema = z
  .object({
    name: z.string().min(1, 'Name is required').max(255),
    requiredReviews: z.number().int().min(1).max(10),
    votingStartAt: z.date().nullable().optional(),
    votingEndAt: z.date().nullable().optional(),
  })
  .refine(
    (data) => {
      if (data.votingStartAt && data.votingEndAt) {
        return data.votingEndAt > data.votingStartAt
      }
      return true
    },
    {
      message: 'End date must be after start date',
      path: ['votingEndAt'],
    }
  )

type UpdateRoundForm = z.infer<typeof updateRoundSchema>

function EditRoundContent({ roundId }: { roundId: string }) {
  const router = useRouter()
  const [criteria, setCriteria] = useState<Criterion[]>([])
  const [criteriaInitialized, setCriteriaInitialized] = useState(false)
  const [formInitialized, setFormInitialized] = useState(false)
  const [roundType, setRoundType] = useState<'FILTERING' | 'EVALUATION' | 'LIVE_EVENT'>('EVALUATION')
  const [roundSettings, setRoundSettings] = useState<Record<string, unknown>>({})

  // Fetch round data - disable refetch on focus to prevent overwriting user's edits
  const { data: round, isLoading: loadingRound } = trpc.round.get.useQuery(
    { id: roundId },
    { refetchOnWindowFocus: false }
  )

  // Fetch evaluation form
  const { data: evaluationForm, isLoading: loadingForm } =
    trpc.round.getEvaluationForm.useQuery({ roundId })

  // Check if evaluations exist
  const { data: hasEvaluations } = trpc.round.hasEvaluations.useQuery({
    roundId,
  })

  const utils = trpc.useUtils()

  // Mutations
  const updateRound = trpc.round.update.useMutation({
    onSuccess: () => {
      // Invalidate cache to ensure fresh data
      utils.round.get.invalidate({ id: roundId })
      utils.round.list.invalidate()
      router.push(`/admin/rounds/${roundId}`)
    },
  })

  const updateEvaluationForm = trpc.round.updateEvaluationForm.useMutation()

  // Initialize form with existing data
  const form = useForm<UpdateRoundForm>({
    resolver: zodResolver(updateRoundSchema),
    defaultValues: {
      name: '',
      requiredReviews: 3,
      votingStartAt: null,
      votingEndAt: null,
    },
  })

  // Update form when round data loads - only initialize once
  useEffect(() => {
    if (round && !formInitialized) {
      form.reset({
        name: round.name,
        requiredReviews: round.requiredReviews,
        votingStartAt: round.votingStartAt ? new Date(round.votingStartAt) : null,
        votingEndAt: round.votingEndAt ? new Date(round.votingEndAt) : null,
      })
      // Set round type and settings
      setRoundType((round.roundType as typeof roundType) || 'EVALUATION')
      setRoundSettings((round.settingsJson as Record<string, unknown>) || {})
      setFormInitialized(true)
    }
  }, [round, form, formInitialized])

  // Initialize criteria from evaluation form
  useEffect(() => {
    if (evaluationForm && !criteriaInitialized) {
      const existingCriteria = evaluationForm.criteriaJson as unknown as Criterion[]
      if (Array.isArray(existingCriteria)) {
        setCriteria(existingCriteria)
      }
      setCriteriaInitialized(true)
    } else if (!loadingForm && !evaluationForm && !criteriaInitialized) {
      setCriteriaInitialized(true)
    }
  }, [evaluationForm, loadingForm, criteriaInitialized])

  const onSubmit = async (data: UpdateRoundForm) => {
    // Update round with type and settings
    await updateRound.mutateAsync({
      id: roundId,
      name: data.name,
      requiredReviews: data.requiredReviews,
      roundType,
      settingsJson: roundSettings,
      votingStartAt: data.votingStartAt ?? null,
      votingEndAt: data.votingEndAt ?? null,
    })

    // Update evaluation form if criteria changed and no evaluations exist
    if (!hasEvaluations && criteria.length > 0) {
      await updateEvaluationForm.mutateAsync({
        roundId,
        criteria,
      })
    }
  }

  const isLoading = loadingRound || loadingForm

  if (isLoading) {
    return <EditRoundSkeleton />
  }

  if (!round) {
    return (
      <div className="space-y-6">
        <Button variant="ghost" asChild className="-ml-4">
          <Link href="/admin/rounds">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Rounds
          </Link>
        </Button>

        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <AlertCircle className="h-12 w-12 text-destructive/50" />
            <p className="mt-2 font-medium">Round Not Found</p>
            <Button asChild className="mt-4">
              <Link href="/admin/rounds">Back to Rounds</Link>
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  const isPending = updateRound.isPending || updateEvaluationForm.isPending
  const isActive = round.status === 'ACTIVE'

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

      <div className="flex items-center gap-3">
        <h1 className="text-2xl font-semibold tracking-tight">Edit Round</h1>
        <Badge variant={isActive ? 'default' : 'secondary'}>
          {round.status}
        </Badge>
      </div>

      {/* Form */}
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          {/* Basic Information */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Basic Information</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Round Name</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="e.g., Round 1 - Semi-Finalists"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="requiredReviews"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Required Reviews per Project</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        min={1}
                        max={10}
                        {...field}
                        onChange={(e) =>
                          field.onChange(parseInt(e.target.value) || 1)
                        }
                      />
                    </FormControl>
                    <FormDescription>
                      Minimum number of evaluations each project should receive
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </CardContent>
          </Card>

          {/* Round Type & Settings */}
          <RoundTypeSettings
            roundType={roundType}
            onRoundTypeChange={setRoundType}
            settings={roundSettings}
            onSettingsChange={setRoundSettings}
          />

          {/* Voting Window */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Voting Window</CardTitle>
              <CardDescription>
                Set when jury members can submit their evaluations
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {isActive && (
                <div className="flex items-center gap-2 rounded-lg bg-amber-500/10 p-3 text-amber-700">
                  <AlertTriangle className="h-4 w-4 shrink-0" />
                  <p className="text-sm">
                    This round is active. Changing the voting window may affect
                    ongoing evaluations.
                  </p>
                </div>
              )}

              <div className="grid gap-4 sm:grid-cols-2">
                <FormField
                  control={form.control}
                  name="votingStartAt"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Start Date & Time</FormLabel>
                      <FormControl>
                        <DateTimePicker
                          value={field.value}
                          onChange={field.onChange}
                          placeholder="Select start date & time"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="votingEndAt"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>End Date & Time</FormLabel>
                      <FormControl>
                        <DateTimePicker
                          value={field.value}
                          onChange={field.onChange}
                          placeholder="Select end date & time"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <p className="text-sm text-muted-foreground">
                Leave empty to disable the voting window enforcement. Past dates are allowed.
              </p>
            </CardContent>
          </Card>

          {/* Evaluation Criteria */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Evaluation Criteria</CardTitle>
              <CardDescription>
                Define the criteria jurors will use to evaluate projects
              </CardDescription>
            </CardHeader>
            <CardContent>
              {hasEvaluations ? (
                <div className="space-y-4">
                  <div className="flex items-center gap-2 rounded-lg bg-amber-500/10 p-3 text-amber-700">
                    <AlertTriangle className="h-4 w-4 shrink-0" />
                    <p className="text-sm">
                      Criteria cannot be modified after evaluations have been
                      submitted. {criteria.length} criteria defined.
                    </p>
                  </div>

                  <EvaluationFormBuilder
                    initialCriteria={criteria}
                    onChange={() => {}}
                    disabled={true}
                  />
                </div>
              ) : (
                <EvaluationFormBuilder
                  initialCriteria={criteria}
                  onChange={setCriteria}
                />
              )}
            </CardContent>
          </Card>

          {/* Error Display */}
          {(updateRound.error || updateEvaluationForm.error) && (
            <Card className="border-destructive">
              <CardContent className="flex items-center gap-2 py-4">
                <AlertCircle className="h-5 w-5 text-destructive" />
                <p className="text-sm text-destructive">
                  {updateRound.error?.message ||
                    updateEvaluationForm.error?.message}
                </p>
              </CardContent>
            </Card>
          )}

          {/* Actions */}
          <div className="flex justify-end gap-3">
            <Button type="button" variant="outline" asChild>
              <Link href={`/admin/rounds/${roundId}`}>Cancel</Link>
            </Button>
            <Button type="submit" disabled={isPending}>
              {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Save Changes
            </Button>
          </div>
        </form>
      </Form>
    </div>
  )
}

function EditRoundSkeleton() {
  return (
    <div className="space-y-6">
      <Skeleton className="h-9 w-36" />

      <div className="flex items-center gap-3">
        <Skeleton className="h-8 w-32" />
        <Skeleton className="h-6 w-16" />
      </div>

      <Card>
        <CardHeader>
          <Skeleton className="h-5 w-40" />
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Skeleton className="h-4 w-24" />
            <Skeleton className="h-10 w-full" />
          </div>
          <div className="space-y-2">
            <Skeleton className="h-4 w-40" />
            <Skeleton className="h-10 w-32" />
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <Skeleton className="h-5 w-32" />
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-2">
            <Skeleton className="h-10 w-full" />
            <Skeleton className="h-10 w-full" />
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <Skeleton className="h-5 w-40" />
        </CardHeader>
        <CardContent>
          <Skeleton className="h-32 w-full" />
        </CardContent>
      </Card>
    </div>
  )
}

export default function EditRoundPage({ params }: PageProps) {
  const { id } = use(params)

  return (
    <Suspense fallback={<EditRoundSkeleton />}>
      <EditRoundContent roundId={id} />
    </Suspense>
  )
}
