import { notFound } from 'next/navigation'
import Link from 'next/link'
import { api } from '@/lib/trpc/server'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { ArrowLeft, Settings, Eye, FileText, Plus } from 'lucide-react'
import { FormEditor } from './form-editor'

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

export default async function FormDetailPage({ params }: FormDetailPageProps) {
  const { id } = await params
  const caller = await api()

  let form
  try {
    form = await caller.applicationForm.get({ id })
  } catch {
    notFound()
  }

  const statusColors = {
    DRAFT: 'bg-gray-100 text-gray-800',
    PUBLISHED: 'bg-green-100 text-green-800',
    CLOSED: 'bg-red-100 text-red-800',
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link href="/admin/forms">
            <Button variant="ghost" size="icon">
              <ArrowLeft className="h-4 w-4" />
            </Button>
          </Link>
          <div>
            <div className="flex items-center gap-2">
              <h1 className="text-2xl font-bold">{form.name}</h1>
              <Badge className={statusColors[form.status as keyof typeof statusColors]}>
                {form.status}
              </Badge>
            </div>
            <p className="text-muted-foreground">
              {form.fields.length} fields - {form._count.submissions} submissions
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {form.publicSlug && form.status === 'PUBLISHED' && (
            <a
              href={`/apply/${form.publicSlug}`}
              target="_blank"
              rel="noopener noreferrer"
            >
              <Button variant="outline">
                <Eye className="mr-2 h-4 w-4" />
                Preview
              </Button>
            </a>
          )}
          <Link href={`/admin/forms/${id}/submissions`}>
            <Button variant="outline">
              <FileText className="mr-2 h-4 w-4" />
              Submissions
            </Button>
          </Link>
        </div>
      </div>

      <FormEditor form={form} />
    </div>
  )
}
