'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { ArrowLeft, Loader2 } from 'lucide-react'
import { toast } from 'sonner'

export default function NewOnboardingFormPage() {
  const router = useRouter()
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [selectedProgramId, setSelectedProgramId] = useState<string>('')

  // Fetch programs for selection
  const { data: programs } = trpc.program.list.useQuery({})

  // Fetch available rounds for the selected program
  const { data: availableRounds } = trpc.applicationForm.getAvailableRounds.useQuery(
    { programId: selectedProgramId || undefined },
    { enabled: true }
  )

  const createForm = trpc.applicationForm.create.useMutation({
    onSuccess: (data) => {
      toast.success('Onboarding form created successfully')
      router.push(`/admin/onboarding/${data.id}`)
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to create form')
      setIsSubmitting(false)
    },
  })

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setIsSubmitting(true)

    const formData = new FormData(e.currentTarget)
    const name = formData.get('name') as string
    const description = formData.get('description') as string
    const publicSlug = formData.get('publicSlug') as string

    createForm.mutate({
      programId: selectedProgramId || null,
      name,
      description: description || undefined,
      publicSlug: publicSlug || undefined,
    })
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Link href="/admin/onboarding">
          <Button variant="ghost" size="icon">
            <ArrowLeft className="h-4 w-4" />
          </Button>
        </Link>
        <div>
          <h1 className="text-2xl font-bold">Create Onboarding Form</h1>
          <p className="text-muted-foreground">
            Set up a new application wizard for project submissions
          </p>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Form Details</CardTitle>
          <CardDescription>
            Configure the basic settings for your onboarding form
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="name">Form Name *</Label>
              <Input
                id="name"
                name="name"
                placeholder="e.g., MOPC 2026 Applications"
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="program">Edition / Program</Label>
              <Select
                value={selectedProgramId}
                onValueChange={setSelectedProgramId}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select a program (optional)" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="">No program</SelectItem>
                  {programs?.map((program) => (
                    <SelectItem key={program.id} value={program.id}>
                      {program.name} {program.year}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <p className="text-sm text-muted-foreground">
                Link to a specific edition to enable project creation
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="description">Description</Label>
              <Textarea
                id="description"
                name="description"
                placeholder="Describe the purpose of this application form..."
                rows={3}
                maxLength={2000}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="publicSlug">Public URL Slug</Label>
              <div className="flex items-center gap-2">
                <span className="text-sm text-muted-foreground">/apply/</span>
                <Input
                  id="publicSlug"
                  name="publicSlug"
                  placeholder="e.g., mopc-2026"
                  className="flex-1"
                />
              </div>
              <p className="text-sm text-muted-foreground">
                Leave empty to generate automatically. Only lowercase letters, numbers, and hyphens.
              </p>
            </div>

            <div className="flex justify-end gap-2 pt-4">
              <Link href="/admin/onboarding">
                <Button type="button" variant="outline">
                  Cancel
                </Button>
              </Link>
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Create Form
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  )
}
