'use client'

import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { FileUploadSlot } from '@/components/applicant/file-upload-slot'
import { ArrowLeft, Lock, Clock, Calendar, AlertCircle } from 'lucide-react'
import { toast } from 'sonner'
import { useState } from 'react'

export default function ApplicantSubmissionWindowPage() {
  const params = useParams()
  const router = useRouter()
  const windowId = params.windowId as string

  const [uploadedFiles, setUploadedFiles] = useState<Record<string, File>>({})

  const { data: window, isLoading } = trpc.round.getById.useQuery(
    { id: windowId },
    { enabled: !!windowId }
  )

  const { data: deadlineStatus } = trpc.round.checkDeadline.useQuery(
    { windowId },
    {
      enabled: !!windowId,
      refetchInterval: 60000, // Refresh every minute
    }
  )

  const handleUpload = (requirementId: string, file: File) => {
    setUploadedFiles(prev => ({ ...prev, [requirementId]: file }))
    toast.success(`File "${file.name}" selected for upload`)
    // In a real implementation, this would trigger file upload
  }

  if (isLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-8 w-64" />
        <Skeleton className="h-96" />
      </div>
    )
  }

  if (!window) {
    return (
      <div className="space-y-6">
        <Button variant="ghost" size="sm" asChild>
          <Link href={'/applicant/competitions' as Route}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back
          </Link>
        </Button>
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <AlertCircle className="h-12 w-12 text-muted-foreground/50 mb-3" />
            <p className="font-medium">Submission window not found</p>
          </CardContent>
        </Card>
      </div>
    )
  }

  const isLocked = deadlineStatus?.status === 'LOCKED' || deadlineStatus?.status === 'CLOSED'
  const deadline = window.windowCloseAt
    ? new Date(window.windowCloseAt)
    : null
  const timeRemaining = deadline ? deadline.getTime() - Date.now() : null
  const daysRemaining = timeRemaining ? Math.floor(timeRemaining / (1000 * 60 * 60 * 24)) : null

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="sm" asChild>
          <Link href={'/applicant/competitions' as Route}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back
          </Link>
        </Button>
        <div>
          <h1 className="text-2xl font-bold tracking-tight">{window.name}</h1>
          <p className="text-muted-foreground mt-1">
            Upload required documents for this submission window
          </p>
        </div>
      </div>

      {/* Deadline card */}
      {deadline && (
        <Card className={isLocked ? 'border-red-200 bg-red-50/50' : 'border-l-4 border-l-amber-500'}>
          <CardContent className="flex items-start gap-3 p-4">
            {isLocked ? (
              <>
                <Lock className="h-5 w-5 text-red-600 shrink-0 mt-0.5" />
                <div className="flex-1">
                  <p className="font-medium text-sm text-red-900">Submission Window Closed</p>
                  <p className="text-sm text-red-700 mt-1">
                    This submission window closed on {deadline.toLocaleDateString()}. No further
                    uploads are allowed.
                  </p>
                </div>
              </>
            ) : (
              <>
                <Clock className="h-5 w-5 text-amber-600 shrink-0 mt-0.5" />
                <div className="flex-1">
                  <p className="font-medium text-sm">Deadline Countdown</p>
                  <div className="flex items-baseline gap-2 mt-1">
                    <span className="text-2xl font-bold tabular-nums text-amber-600">
                      {daysRemaining !== null ? daysRemaining : '—'}
                    </span>
                    <span className="text-sm text-muted-foreground">
                      day{daysRemaining !== 1 ? 's' : ''} remaining
                    </span>
                  </div>
                  <p className="text-xs text-muted-foreground mt-1">
                    Due: {deadline.toLocaleString()}
                  </p>
                </div>
              </>
            )}
          </CardContent>
        </Card>
      )}

      {/* File requirements */}
      <Card>
        <CardHeader>
          <CardTitle>File Requirements</CardTitle>
          <CardDescription>
            Upload the required files below. {isLocked && 'Viewing only - window is closed.'}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* File requirements would be fetched separately in a real implementation */}
          {false ? (
            [].map((req: any) => (
              <FileUploadSlot
                key={req.id}
                requirement={{
                  id: req.id,
                  label: req.label,
                  description: req.description,
                  mimeTypes: req.mimeTypes || [],
                  maxSizeMb: req.maxSizeMb,
                  required: req.required || false,
                }}
                isLocked={isLocked}
                onUpload={(file) => handleUpload(req.id, file)}
              />
            ))
          ) : (
            <div className="text-center py-8">
              <Calendar className="h-12 w-12 text-muted-foreground/50 mx-auto mb-3" />
              <p className="text-sm text-muted-foreground">
                No file requirements defined for this window
              </p>
            </div>
          )}
        </CardContent>
      </Card>

      {!isLocked && (
        <div className="flex justify-end gap-3">
          <Button variant="outline">Save Draft</Button>
          <Button className="bg-brand-blue hover:bg-brand-blue-light">
            Submit All Files
          </Button>
        </div>
      )}
    </div>
  )
}
