"use client"

import { useState, useEffect } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  FileText,
  CreditCard,
  CheckCircle,
  XCircle,
  Clock,
  Search,
  Download,
  Eye,
  Mail,
  Users,
  TrendingUp,
  Filter,
} from "lucide-react"
import { AdminLayout } from "@/components/admin-layout"

interface Application {
  id: string
  studentName: string
  email: string
  program: string
  status: "pending" | "under-review" | "approved" | "rejected"
  submittedAt: string
  isInternational: boolean
  completionPercentage: number
}

interface Voucher {
  id: string
  code: string
  email: string
  amount: number
  status: "active" | "used" | "expired"
  createdAt: string
  usedAt?: string
}

export default function AdminDashboard() {
  const [applications, setApplications] = useState<Application[]>([])
  const [vouchers, setVouchers] = useState<Voucher[]>([])
  const [searchTerm, setSearchTerm] = useState("")
  const [selectedStatus, setSelectedStatus] = useState<string>("all")
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    // Simulate fetching data
    setTimeout(() => {
      setApplications([
        {
          id: "1",
          studentName: "John Doe",
          email: "john@example.com",
          program: "Computer Science",
          status: "pending",
          submittedAt: "2024-01-15T10:30:00Z",
          isInternational: false,
          completionPercentage: 100,
        },
        {
          id: "2",
          studentName: "Jane Smith",
          email: "jane@example.com",
          program: "Business Administration",
          status: "under-review",
          submittedAt: "2024-01-14T14:20:00Z",
          isInternational: true,
          completionPercentage: 95,
        },
        {
          id: "3",
          studentName: "Mike Johnson",
          email: "mike@example.com",
          program: "Engineering",
          status: "approved",
          submittedAt: "2024-01-13T09:15:00Z",
          isInternational: false,
          completionPercentage: 100,
        },
      ])

      setVouchers([
        {
          id: "1",
          code: "FU2024001",
          email: "john@example.com",
          amount: 5000,
          status: "used",
          createdAt: "2024-01-10T08:00:00Z",
          usedAt: "2024-01-15T10:30:00Z",
        },
        {
          id: "2",
          code: "FU2024002",
          email: "jane@example.com",
          amount: 5000,
          status: "used",
          createdAt: "2024-01-11T09:00:00Z",
          usedAt: "2024-01-14T14:20:00Z",
        },
        {
          id: "3",
          code: "FU2024003",
          email: "sarah@example.com",
          amount: 5000,
          status: "active",
          createdAt: "2024-01-16T11:00:00Z",
        },
      ])
      setLoading(false)
    }, 1000)
  }, [])

  const getStatusColor = (status: string) => {
    switch (status) {
      case "pending":
        return "bg-yellow-100 text-yellow-800"
      case "under-review":
        return "bg-blue-100 text-blue-800"
      case "approved":
        return "bg-green-100 text-green-800"
      case "rejected":
        return "bg-red-100 text-red-800"
      case "active":
        return "bg-green-100 text-green-800"
      case "used":
        return "bg-gray-100 text-gray-800"
      case "expired":
        return "bg-red-100 text-red-800"
      default:
        return "bg-gray-100 text-gray-800"
    }
  }

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "approved":
        return <CheckCircle className="h-4 w-4" />
      case "rejected":
        return <XCircle className="h-4 w-4" />
      case "under-review":
        return <Clock className="h-4 w-4" />
      default:
        return <Clock className="h-4 w-4" />
    }
  }

  const filteredApplications = applications.filter((app) => {
    const matchesSearch =
      app.studentName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      app.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
      app.program.toLowerCase().includes(searchTerm.toLowerCase())
    const matchesStatus = selectedStatus === "all" || app.status === selectedStatus
    return matchesSearch && matchesStatus
  })

  const stats = {
    totalApplications: applications.length,
    pendingApplications: applications.filter((app) => app.status === "pending").length,
    approvedApplications: applications.filter((app) => app.status === "approved").length,
    internationalApplications: applications.filter((app) => app.isInternational).length,
    totalVouchers: vouchers.length,
    activeVouchers: vouchers.filter((v) => v.status === "active").length,
    usedVouchers: vouchers.filter((v) => v.status === "used").length,
    totalRevenue: vouchers.filter((v) => v.status === "used").reduce((sum, v) => sum + v.amount, 0),
  }

  if (loading) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-accent"></div>
        </div>
      </AdminLayout>
    )
  }

  return (
    <AdminLayout>
      <div className="space-y-8 animate-fade-in">
        <div className="space-y-2">
          <h1 className="text-4xl font-bold text-foreground tracking-tight">Admin Dashboard</h1>
          <p className="text-lg text-muted-foreground">
            Manage applications, vouchers, and admissions with comprehensive insights
          </p>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          <Card className="card-hover border-border/50 bg-card/50 backdrop-blur-sm">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-3">
              <CardTitle className="text-sm font-medium text-card-foreground">Total Applications</CardTitle>
              <div className="p-2 bg-accent/10 rounded-lg">
                <FileText className="h-4 w-4 text-accent" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold text-foreground">{stats.totalApplications}</div>
              <p className="text-sm text-muted-foreground mt-1">
                <span className="text-accent font-medium">{stats.internationalApplications}</span> international
              </p>
            </CardContent>
          </Card>

          <Card className="card-hover border-border/50 bg-card/50 backdrop-blur-sm">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-3">
              <CardTitle className="text-sm font-medium text-card-foreground">Pending Review</CardTitle>
              <div className="p-2 bg-yellow-500/10 rounded-lg">
                <Clock className="h-4 w-4 text-yellow-500" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold text-foreground">{stats.pendingApplications}</div>
              <p className="text-sm text-muted-foreground mt-1">Awaiting review</p>
            </CardContent>
          </Card>

          <Card className="card-hover border-border/50 bg-card/50 backdrop-blur-sm">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-3">
              <CardTitle className="text-sm font-medium text-card-foreground">Approved</CardTitle>
              <div className="p-2 bg-green-500/10 rounded-lg">
                <CheckCircle className="h-4 w-4 text-green-500" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold text-foreground">{stats.approvedApplications}</div>
              <p className="text-sm text-muted-foreground mt-1">Successfully approved</p>
            </CardContent>
          </Card>

          <Card className="card-hover border-border/50 bg-card/50 backdrop-blur-sm">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-3">
              <CardTitle className="text-sm font-medium text-card-foreground">Revenue</CardTitle>
              <div className="p-2 bg-accent/10 rounded-lg">
                <TrendingUp className="h-4 w-4 text-accent" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold text-foreground">₦{stats.totalRevenue.toLocaleString()}</div>
              <p className="text-sm text-muted-foreground mt-1">
                From <span className="text-accent font-medium">{stats.usedVouchers}</span> vouchers
              </p>
            </CardContent>
          </Card>
        </div>

        <Tabs defaultValue="applications" className="space-y-6">
          <TabsList className="grid w-full grid-cols-3 lg:w-fit lg:grid-cols-3 bg-muted/50 p-1">
            <TabsTrigger
              value="applications"
              className="data-[state=active]:bg-accent data-[state=active]:text-accent-foreground"
            >
              <Users className="h-4 w-4 mr-2" />
              Applications
            </TabsTrigger>
            <TabsTrigger
              value="vouchers"
              className="data-[state=active]:bg-accent data-[state=active]:text-accent-foreground"
            >
              <CreditCard className="h-4 w-4 mr-2" />
              Vouchers
            </TabsTrigger>
            <TabsTrigger
              value="reports"
              className="data-[state=active]:bg-accent data-[state=active]:text-accent-foreground"
            >
              <FileText className="h-4 w-4 mr-2" />
              Reports
            </TabsTrigger>
          </TabsList>

          <TabsContent value="applications" className="space-y-6 animate-slide-in">
            <Card className="border-border/50 bg-card/50 backdrop-blur-sm">
              <CardHeader className="border-b border-border/50">
                <CardTitle className="text-xl text-foreground">Application Management</CardTitle>
                <CardDescription className="text-base text-muted-foreground">
                  Review and manage student applications with advanced filtering
                </CardDescription>
              </CardHeader>
              <CardContent className="pt-6">
                <div className="flex flex-col sm:flex-row gap-4 mb-8">
                  <div className="relative flex-1">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input
                      placeholder="Search by name, email, or program..."
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                      className="pl-10 bg-input border-border/50 focus:border-accent"
                    />
                  </div>
                  <div className="flex gap-2">
                    <div className="relative">
                      <Filter className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                      <select
                        value={selectedStatus}
                        onChange={(e) => setSelectedStatus(e.target.value)}
                        className="pl-10 pr-8 py-2 bg-input border border-border/50 rounded-lg text-foreground focus:outline-none focus:ring-2 focus:ring-accent focus:border-accent appearance-none"
                      >
                        <option value="all">All Status</option>
                        <option value="pending">Pending</option>
                        <option value="under-review">Under Review</option>
                        <option value="approved">Approved</option>
                        <option value="rejected">Rejected</option>
                      </select>
                    </div>
                    <Button variant="outline" className="bg-transparent border-border/50">
                      <Download className="h-4 w-4 mr-2" />
                      Export
                    </Button>
                  </div>
                </div>

                <div className="overflow-x-auto rounded-lg border border-border/50">
                  <table className="w-full">
                    <thead className="bg-muted/30">
                      <tr>
                        <th className="text-left p-4 font-semibold text-foreground border-b border-border/50">
                          Student
                        </th>
                        <th className="text-left p-4 font-semibold text-foreground border-b border-border/50">
                          Program
                        </th>
                        <th className="text-left p-4 font-semibold text-foreground border-b border-border/50">Type</th>
                        <th className="text-left p-4 font-semibold text-foreground border-b border-border/50">
                          Status
                        </th>
                        <th className="text-left p-4 font-semibold text-foreground border-b border-border/50">
                          Submitted
                        </th>
                        <th className="text-left p-4 font-semibold text-foreground border-b border-border/50">
                          Actions
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {filteredApplications.map((app, index) => (
                        <tr key={app.id} className="border-b border-border/30 hover:bg-muted/20 transition-colors">
                          <td className="p-4">
                            <div className="space-y-1">
                              <div className="font-medium text-foreground">{app.studentName}</div>
                              <div className="text-sm text-muted-foreground">{app.email}</div>
                            </div>
                          </td>
                          <td className="p-4 text-foreground">{app.program}</td>
                          <td className="p-4">
                            <Badge
                              variant={app.isInternational ? "secondary" : "outline"}
                              className={
                                app.isInternational
                                  ? "bg-accent/20 text-accent border-accent/30"
                                  : "bg-muted/50 text-muted-foreground border-border/50"
                              }
                            >
                              {app.isInternational ? "International" : "Local"}
                            </Badge>
                          </td>
                          <td className="p-4">
                            <Badge className={`${getStatusColor(app.status)} border-0`}>
                              <div className="flex items-center gap-1.5">
                                {getStatusIcon(app.status)}
                                <span className="capitalize">{app.status.replace("-", " ")}</span>
                              </div>
                            </Badge>
                          </td>
                          <td className="p-4 text-sm text-muted-foreground">
                            {new Date(app.submittedAt).toLocaleDateString()}
                          </td>
                          <td className="p-4">
                            <div className="flex gap-2">
                              <Button
                                size="sm"
                                variant="outline"
                                className="bg-transparent border-border/50 hover:bg-accent/10 hover:border-accent/50"
                              >
                                <Eye className="h-4 w-4" />
                              </Button>
                              <Button
                                size="sm"
                                variant="outline"
                                className="bg-transparent border-border/50 hover:bg-accent/10 hover:border-accent/50"
                              >
                                <Download className="h-4 w-4" />
                              </Button>
                              <Button
                                size="sm"
                                variant="outline"
                                className="bg-transparent border-border/50 hover:bg-accent/10 hover:border-accent/50"
                              >
                                <Mail className="h-4 w-4" />
                              </Button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="vouchers" className="space-y-6 animate-slide-in">
            <Card className="border-border/50 bg-card/50 backdrop-blur-sm">
              <CardHeader className="border-b border-border/50">
                <CardTitle className="text-xl text-foreground">Voucher Management</CardTitle>
                <CardDescription className="text-base text-muted-foreground">
                  Generate and manage application vouchers
                </CardDescription>
              </CardHeader>
              <CardContent className="pt-6">
                <div className="flex justify-between items-center mb-8">
                  <div className="relative flex-1 max-w-sm">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input
                      placeholder="Search vouchers..."
                      className="pl-10 bg-input border-border/50 focus:border-accent"
                    />
                  </div>
                  <Button className="bg-accent hover:bg-accent/90 text-accent-foreground">
                    <CreditCard className="h-4 w-4 mr-2" />
                    Generate New Voucher
                  </Button>
                </div>

                <div className="overflow-x-auto rounded-lg border border-border/50">
                  <table className="w-full">
                    <thead className="bg-muted/30">
                      <tr>
                        <th className="text-left p-4 font-semibold text-foreground border-b border-border/50">
                          Voucher Code
                        </th>
                        <th className="text-left p-4 font-semibold text-foreground border-b border-border/50">Email</th>
                        <th className="text-left p-4 font-semibold text-foreground border-b border-border/50">
                          Amount
                        </th>
                        <th className="text-left p-4 font-semibold text-foreground border-b border-border/50">
                          Status
                        </th>
                        <th className="text-left p-4 font-semibold text-foreground border-b border-border/50">
                          Created
                        </th>
                        <th className="text-left p-4 font-semibold text-foreground border-b border-border/50">Used</th>
                      </tr>
                    </thead>
                    <tbody>
                      {vouchers.map((voucher) => (
                        <tr key={voucher.id} className="border-b border-border/30 hover:bg-muted/20 transition-colors">
                          <td className="p-4 font-mono text-accent">{voucher.code}</td>
                          <td className="p-4 text-foreground">{voucher.email}</td>
                          <td className="p-4 font-semibold text-foreground">₦{voucher.amount.toLocaleString()}</td>
                          <td className="p-4">
                            <Badge className={`${getStatusColor(voucher.status)} border-0 capitalize`}>
                              {voucher.status}
                            </Badge>
                          </td>
                          <td className="p-4 text-sm text-muted-foreground">
                            {new Date(voucher.createdAt).toLocaleDateString()}
                          </td>
                          <td className="p-4 text-sm text-muted-foreground">
                            {voucher.usedAt ? new Date(voucher.usedAt).toLocaleDateString() : "—"}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="reports" className="space-y-6 animate-slide-in">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <Card className="card-hover border-border/50 bg-card/50 backdrop-blur-sm">
                <CardHeader className="border-b border-border/50">
                  <CardTitle className="text-xl text-foreground">Application Reports</CardTitle>
                  <CardDescription className="text-base text-muted-foreground">
                    Download application data and comprehensive reports
                  </CardDescription>
                </CardHeader>
                <CardContent className="pt-6 space-y-4">
                  <Button
                    variant="outline"
                    className="w-full justify-start bg-transparent border-border/50 hover:bg-accent/10 hover:border-accent/50"
                  >
                    <Download className="h-4 w-4 mr-3" />
                    Export All Applications
                  </Button>
                  <Button
                    variant="outline"
                    className="w-full justify-start bg-transparent border-border/50 hover:bg-accent/10 hover:border-accent/50"
                  >
                    <Download className="h-4 w-4 mr-3" />
                    Export Pending Applications
                  </Button>
                  <Button
                    variant="outline"
                    className="w-full justify-start bg-transparent border-border/50 hover:bg-accent/10 hover:border-accent/50"
                  >
                    <Download className="h-4 w-4 mr-3" />
                    Export International Applications
                  </Button>
                </CardContent>
              </Card>

              <Card className="card-hover border-border/50 bg-card/50 backdrop-blur-sm">
                <CardHeader className="border-b border-border/50">
                  <CardTitle className="text-xl text-foreground">Financial Reports</CardTitle>
                  <CardDescription className="text-base text-muted-foreground">
                    Download voucher and payment transaction reports
                  </CardDescription>
                </CardHeader>
                <CardContent className="pt-6 space-y-4">
                  <Button
                    variant="outline"
                    className="w-full justify-start bg-transparent border-border/50 hover:bg-accent/10 hover:border-accent/50"
                  >
                    <Download className="h-4 w-4 mr-3" />
                    Export Voucher Sales
                  </Button>
                  <Button
                    variant="outline"
                    className="w-full justify-start bg-transparent border-border/50 hover:bg-accent/10 hover:border-accent/50"
                  >
                    <Download className="h-4 w-4 mr-3" />
                    Export Payment Transactions
                  </Button>
                  <Button
                    variant="outline"
                    className="w-full justify-start bg-transparent border-border/50 hover:bg-accent/10 hover:border-accent/50"
                  >
                    <Download className="h-4 w-4 mr-3" />
                    Export Revenue Report
                  </Button>
                </CardContent>
              </Card>
            </div>
          </TabsContent>
        </Tabs>
      </div>
    </AdminLayout>
  )
}
