"use client"

import { useState } from "react"
import { DashboardLayout } from "@/components/dashboard-layout"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Separator } from "@/components/ui/separator"
import {
  CheckCircle,
  AlertCircle,
  Send,
  Edit,
  User,
  MapPin,
  BookOpen,
  Info,
  Users,
  Award,
  UserCheck,
  Upload,
  FileCheck,
  ArrowLeft,
} from "lucide-react"
import Link from "next/link"
import { useRouter } from "next/navigation"

// Mock data - in real app this would come from API/state management
const mockApplicationData = {
  biodata: {
    completed: true,
    data: {
      firstName: "John",
      middleName: "Michael",
      lastName: "Doe",
      dateOfBirth: "1995-06-15",
      gender: "male",
      nationality: "Nigerian",
      stateOfOrigin: "Lagos",
      phoneNumber: "+234 801 234 5678",
      email: "john.doe@email.com",
      maritalStatus: "single",
      religion: "Christianity",
    },
  },
  address: {
    completed: true,
    data: {
      permanentAddress: "123 Main Street, Victoria Island",
      permanentCity: "Lagos",
      permanentState: "Lagos",
      permanentCountry: "Nigeria",
      sameAsPermanent: true,
    },
  },
  education: {
    completed: true,
    data: [
      {
        institution: "Lagos State University",
        qualification: "Bachelor's Degree",
        grade: "Second Class Upper",
        yearCompleted: "2018",
        subjects: "Computer Science",
      },
      {
        institution: "Federal Government College",
        qualification: "WAEC/SSCE",
        grade: "5 Credits",
        yearCompleted: "2012",
        subjects: "Mathematics, English, Physics, Chemistry, Biology",
      },
    ],
  },
  program: {
    completed: true,
    data: {
      firstChoice: "Computer Science",
      secondChoice: "Software Engineering",
      studyMode: "full-time",
      entryLevel: "100",
      jamb: "285",
      personalStatement: "I am passionate about technology and innovation...",
    },
  },
  guardian: {
    completed: true,
    data: {
      guardianName: "Mary Doe",
      relationship: "mother",
      occupation: "Teacher",
      phoneNumber: "+234 803 456 7890",
      email: "mary.doe@email.com",
      emergencyName: "Mary Doe",
      emergencyPhone: "+234 803 456 7890",
    },
  },
  scholarship: {
    completed: true,
    data: {
      applyingForScholarship: true,
      scholarshipType: "need",
      financialNeed: "My family has limited financial resources...",
    },
  },
  referee: {
    completed: true,
    data: [
      {
        name: "Dr. Sarah Johnson",
        title: "Professor",
        organization: "Lagos State University",
        relationship: "teacher",
        phoneNumber: "+234 805 123 4567",
        email: "sarah.johnson@lasu.edu.ng",
      },
      {
        name: "Mr. David Wilson",
        title: "Principal",
        organization: "Federal Government College",
        relationship: "principal",
        phoneNumber: "+234 807 234 5678",
        email: "david.wilson@fgc.edu.ng",
      },
    ],
  },
  uploads: {
    completed: true,
    data: {
      passport: { name: "passport_photo.jpg", uploaded: true },
      certificate: { name: "degree_certificate.pdf", uploaded: true },
      transcript: { name: "academic_transcript.pdf", uploaded: true },
      birth_certificate: { name: "birth_certificate.pdf", uploaded: true },
      identification: { name: "national_id.pdf", uploaded: true },
    },
  },
  declaration: {
    completed: true,
    data: {
      allDeclarationsAccepted: true,
      signature: "John Michael Doe",
      date: "2024-01-15",
    },
  },
}

export default function ReviewPage() {
  const router = useRouter()
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [showConfirmation, setShowConfirmation] = useState(false)

  const sections = [
    {
      key: "biodata",
      title: "Personal Information",
      icon: User,
      href: "/dashboard/applications/biodata",
    },
    {
      key: "address",
      title: "Address Information",
      icon: MapPin,
      href: "/dashboard/applications/address",
    },
    {
      key: "education",
      title: "Education Background",
      icon: BookOpen,
      href: "/dashboard/applications/education",
    },
    {
      key: "program",
      title: "Program Information",
      icon: Info,
      href: "/dashboard/applications/program",
    },
    {
      key: "guardian",
      title: "Guardian Information",
      icon: Users,
      href: "/dashboard/applications/guardian",
    },
    {
      key: "scholarship",
      title: "Scholarship Information",
      icon: Award,
      href: "/dashboard/applications/scholarship",
    },
    {
      key: "referee",
      title: "Referee Information",
      icon: UserCheck,
      href: "/dashboard/applications/referee",
    },
    {
      key: "uploads",
      title: "Document Uploads",
      icon: Upload,
      href: "/dashboard/applications/uploads",
    },
    {
      key: "declaration",
      title: "Declaration",
      icon: FileCheck,
      href: "/dashboard/applications/declaration",
    },
  ]

  const completedSections = sections.filter((section) => mockApplicationData[section.key]?.completed)
  const incompleteSections = sections.filter((section) => !mockApplicationData[section.key]?.completed)
  const allSectionsComplete = incompleteSections.length === 0

  const handleSubmit = async () => {
    if (!allSectionsComplete) {
      alert("Please complete all required sections before submitting.")
      return
    }

    setIsSubmitting(true)
    // Simulate API call
    setTimeout(() => {
      setIsSubmitting(false)
      setShowConfirmation(true)
    }, 3000)
  }

  const handleBackToDashboard = () => {
    router.push("/dashboard")
  }

  if (showConfirmation) {
    return (
      <DashboardLayout>
        <div className="max-w-4xl mx-auto">
          <Card className="border-green-200 bg-green-50">
            <CardContent className="pt-6">
              <div className="text-center space-y-4">
                <div className="mx-auto w-16 h-16 bg-green-100 rounded-full flex items-center justify-center">
                  <CheckCircle className="h-8 w-8 text-green-600" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-green-800">Application Submitted Successfully!</h1>
                  <p className="text-green-700 mt-2">
                    Your application has been submitted and is now under review. You will receive a confirmation email
                    shortly.
                  </p>
                </div>
                <div className="bg-white p-4 rounded-lg border border-green-200">
                  <p className="text-sm text-green-700">
                    <strong>Application ID:</strong> FU2024-{Math.random().toString(36).substr(2, 9).toUpperCase()}
                  </p>
                  <p className="text-sm text-green-700">
                    <strong>Submitted:</strong>{" "}
                    {new Date().toLocaleDateString("en-US", {
                      year: "numeric",
                      month: "long",
                      day: "numeric",
                      hour: "2-digit",
                      minute: "2-digit",
                    })}
                  </p>
                </div>
                <div className="space-y-2">
                  <p className="text-sm text-green-700">
                    You can track your admission status in the dashboard. We will notify you of any updates via email.
                  </p>
                  <Button onClick={handleBackToDashboard} className="bg-green-600 hover:bg-green-700">
                    Back to Dashboard
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </DashboardLayout>
    )
  }

  return (
    <DashboardLayout>
      <div className="max-w-6xl mx-auto space-y-6">
        <div>
          <h1 className="text-3xl font-bold text-primary">Review & Submit Application</h1>
          <p className="text-muted-foreground">
            Review all sections of your application before final submission. You can edit any section if needed.
          </p>
        </div>

        {/* Application Status Overview */}
        <Card>
          <CardHeader>
            <CardTitle>Application Status</CardTitle>
            <CardDescription>Overview of your application completion status</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid md:grid-cols-3 gap-4 mb-4">
              <div className="text-center">
                <div className="text-2xl font-bold text-green-600">{completedSections.length}</div>
                <div className="text-sm text-muted-foreground">Completed Sections</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-orange-600">{incompleteSections.length}</div>
                <div className="text-sm text-muted-foreground">Pending Sections</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-blue-600">
                  {Math.round((completedSections.length / sections.length) * 100)}%
                </div>
                <div className="text-sm text-muted-foreground">Overall Progress</div>
              </div>
            </div>

            {!allSectionsComplete && (
              <Alert>
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>
                  You have {incompleteSections.length} incomplete section(s). Please complete all sections before
                  submitting your application.
                </AlertDescription>
              </Alert>
            )}

            {allSectionsComplete && (
              <Alert className="border-green-200 bg-green-50">
                <CheckCircle className="h-4 w-4 text-green-600" />
                <AlertDescription className="text-green-700">
                  All sections completed! Your application is ready for submission.
                </AlertDescription>
              </Alert>
            )}
          </CardContent>
        </Card>

        {/* Section Status Grid */}
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
          {sections.map((section) => {
            const sectionData = mockApplicationData[section.key]
            const Icon = section.icon
            const isComplete = sectionData?.completed

            return (
              <Card key={section.key} className={isComplete ? "border-green-200" : "border-orange-200"}>
                <CardContent className="p-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <Icon className={`h-5 w-5 ${isComplete ? "text-green-600" : "text-orange-600"}`} />
                      <div>
                        <h3 className="font-medium text-sm">{section.title}</h3>
                        <Badge variant={isComplete ? "default" : "secondary"} className="text-xs">
                          {isComplete ? "Complete" : "Incomplete"}
                        </Badge>
                      </div>
                    </div>
                    <Button asChild variant="ghost" size="sm">
                      <Link href={section.href}>
                        <Edit className="h-4 w-4" />
                      </Link>
                    </Button>
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>

        {/* Application Summary */}
        <Card>
          <CardHeader>
            <CardTitle>Application Summary</CardTitle>
            <CardDescription>Read-only summary of your application details</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Personal Information */}
            <div>
              <h3 className="font-semibold text-primary mb-3 flex items-center gap-2">
                <User className="h-4 w-4" />
                Personal Information
              </h3>
              <div className="grid md:grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="text-muted-foreground">Full Name:</span>{" "}
                  {`${mockApplicationData.biodata.data.firstName} ${mockApplicationData.biodata.data.middleName} ${mockApplicationData.biodata.data.lastName}`}
                </div>
                <div>
                  <span className="text-muted-foreground">Date of Birth:</span>{" "}
                  {new Date(mockApplicationData.biodata.data.dateOfBirth).toLocaleDateString()}
                </div>
                <div>
                  <span className="text-muted-foreground">Gender:</span>{" "}
                  {mockApplicationData.biodata.data.gender.charAt(0).toUpperCase() +
                    mockApplicationData.biodata.data.gender.slice(1)}
                </div>
                <div>
                  <span className="text-muted-foreground">Nationality:</span>{" "}
                  {mockApplicationData.biodata.data.nationality}
                </div>
                <div>
                  <span className="text-muted-foreground">Phone:</span> {mockApplicationData.biodata.data.phoneNumber}
                </div>
                <div>
                  <span className="text-muted-foreground">Email:</span> {mockApplicationData.biodata.data.email}
                </div>
              </div>
            </div>

            <Separator />

            {/* Program Information */}
            <div>
              <h3 className="font-semibold text-primary mb-3 flex items-center gap-2">
                <Info className="h-4 w-4" />
                Program Choices
              </h3>
              <div className="grid md:grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="text-muted-foreground">First Choice:</span>{" "}
                  {mockApplicationData.program.data.firstChoice}
                </div>
                <div>
                  <span className="text-muted-foreground">Second Choice:</span>{" "}
                  {mockApplicationData.program.data.secondChoice}
                </div>
                <div>
                  <span className="text-muted-foreground">Study Mode:</span>{" "}
                  {mockApplicationData.program.data.studyMode.charAt(0).toUpperCase() +
                    mockApplicationData.program.data.studyMode.slice(1).replace("-", " ")}
                </div>
                <div>
                  <span className="text-muted-foreground">Entry Level:</span>{" "}
                  {mockApplicationData.program.data.entryLevel} Level
                </div>
              </div>
            </div>

            <Separator />

            {/* Education Background */}
            <div>
              <h3 className="font-semibold text-primary mb-3 flex items-center gap-2">
                <BookOpen className="h-4 w-4" />
                Education Background
              </h3>
              <div className="space-y-3">
                {mockApplicationData.education.data.map((edu, index) => (
                  <div key={index} className="p-3 bg-muted/50 rounded-lg">
                    <div className="grid md:grid-cols-2 gap-2 text-sm">
                      <div>
                        <span className="text-muted-foreground">Institution:</span> {edu.institution}
                      </div>
                      <div>
                        <span className="text-muted-foreground">Qualification:</span> {edu.qualification}
                      </div>
                      <div>
                        <span className="text-muted-foreground">Grade:</span> {edu.grade}
                      </div>
                      <div>
                        <span className="text-muted-foreground">Year:</span> {edu.yearCompleted}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <Separator />

            {/* Documents */}
            <div>
              <h3 className="font-semibold text-primary mb-3 flex items-center gap-2">
                <Upload className="h-4 w-4" />
                Uploaded Documents
              </h3>
              <div className="grid md:grid-cols-2 gap-2 text-sm">
                {Object.entries(mockApplicationData.uploads.data).map(([key, file]) => (
                  <div key={key} className="flex items-center justify-between">
                    <span className="text-muted-foreground">
                      {key.replace("_", " ").charAt(0).toUpperCase() + key.replace("_", " ").slice(1)}:
                    </span>
                    <Badge variant="default" className="text-xs">
                      <CheckCircle className="h-3 w-3 mr-1" />
                      Uploaded
                    </Badge>
                  </div>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Submit Section */}
        <Card>
          <CardHeader>
            <CardTitle>Final Submission</CardTitle>
            <CardDescription>
              Once you submit your application, you will not be able to make changes. Please ensure all information is
              correct.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="p-4 bg-muted/50 rounded-lg">
                <h4 className="font-medium mb-2">Before you submit:</h4>
                <ul className="text-sm text-muted-foreground space-y-1">
                  <li>✓ All required sections are completed</li>
                  <li>✓ All required documents are uploaded</li>
                  <li>✓ All information provided is accurate</li>
                  <li>✓ Declaration has been signed</li>
                </ul>
              </div>

              <div className="flex justify-between items-center">
                <Button variant="outline" onClick={() => router.push("/dashboard")}>
                  <ArrowLeft className="mr-2 h-4 w-4" />
                  Back to Dashboard
                </Button>
                <Button
                  onClick={handleSubmit}
                  disabled={!allSectionsComplete || isSubmitting}
                  className="bg-accent hover:bg-accent/90"
                  size="lg"
                >
                  {isSubmitting ? (
                    <>
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                      Submitting Application...
                    </>
                  ) : (
                    <>
                      <Send className="mr-2 h-4 w-4" />
                      Submit Application
                    </>
                  )}
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </DashboardLayout>
  )
}
