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, Download, Trash2 } from 'lucide-react'
import { formatDate } from '@/lib/utils'

interface SubmissionDetailPageProps {
  params: Promise<{ id: string; submissionId: string }>
}

const statusColors = {
  SUBMITTED: 'bg-blue-100 text-blue-800',
  REVIEWED: 'bg-yellow-100 text-yellow-800',
  APPROVED: 'bg-green-100 text-green-800',
  REJECTED: 'bg-red-100 text-red-800',
}

export default async function SubmissionDetailPage({ params }: SubmissionDetailPageProps) {
  const { id, submissionId } = await params
  const caller = await api()

  let submission
  try {
    submission = await caller.applicationForm.getSubmission({ id: submissionId })
  } catch {
    notFound()
  }

  const data = submission.dataJson as Record<string, unknown>

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link href={`/admin/forms/${id}/submissions`}>
            <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">
                {submission.name || submission.email || 'Anonymous Submission'}
              </h1>
              <Badge className={statusColors[submission.status as keyof typeof statusColors]}>
                {submission.status}
              </Badge>
            </div>
            <p className="text-muted-foreground">
              Submitted {formatDate(submission.createdAt)}
            </p>
          </div>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Submission Data</CardTitle>
          <CardDescription>
            All fields submitted in this application
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {submission.form.fields.map((field) => {
              const value = data[field.name]
              return (
                <div key={field.id} className="border-b pb-4 last:border-0">
                  <div className="font-medium text-sm text-muted-foreground">
                    {field.label}
                  </div>
                  <div className="mt-1">
                    {value !== undefined && value !== null && value !== '' ? (
                      typeof value === 'object' ? (
                        <pre className="text-sm bg-muted p-2 rounded">
                          {JSON.stringify(value, null, 2)}
                        </pre>
                      ) : (
                        <span>{String(value)}</span>
                      )
                    ) : (
                      <span className="text-muted-foreground italic">Not provided</span>
                    )}
                  </div>
                </div>
              )
            })}
          </div>
        </CardContent>
      </Card>

      {submission.files.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Attached Files</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {submission.files.map((file) => (
                <div
                  key={file.id}
                  className="flex items-center justify-between p-3 border rounded-lg"
                >
                  <div>
                    <div className="font-medium">{file.fileName}</div>
                    <div className="text-sm text-muted-foreground">
                      {file.size ? `${(file.size / 1024).toFixed(1)} KB` : 'Unknown size'}
                    </div>
                  </div>
                  <Button variant="ghost" size="icon">
                    <Download className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
