'use client'

import { useEffect, useState } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { 
  Users, 
  FileText, 
  Clock, 
  CheckCircle, 
  AlertCircle, 
  BarChart3,
  Settings,
  Building,
  Mail,
  Phone,
  Globe
} from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { AdminSidebar } from '@/components/admin-sidebar'
import { useAdminAuth } from '@/hooks/useAdminAuth'

interface DashboardStats {
  totalRequests: number
  pendingRequests: number
  inProgressRequests: number
  completedRequests: number
  totalUsers: number
  recentRequests: Array<{
    id: string
    trackingNumber: string
    service: {
      title: string
    }
    user: {
      name: string
    }
    status: string
    createdAt: string
  }>
}

interface SystemSettings {
  siteName: string
  siteDescription: string
  contactEmail: string
  contactPhone: string
  address: string
  workingHours: string
  timezone: string
  language: string
  emailNotifications: boolean
  smsNotifications: boolean
  autoAssignment: boolean
  maintenanceMode: boolean
  maxFileSize: number
  allowedFileTypes: string[]
  sessionTimeout: number
  passwordMinLength: number
  requireEmailVerification: boolean
}

export default function AdminDashboard() {
  const router = useRouter()
  const { user, loading, isAuthenticated, logout, getAuthHeaders } = useAdminAuth()
  const [stats, setStats] = useState<DashboardStats | null>(null)
  const [settings, setSettings] = useState<SystemSettings | null>(null)

  useEffect(() => {
    if (!loading && !isAuthenticated) {
      router.push('/admin/login')
      return
    }

    if (isAuthenticated) {
      fetchDashboardStats()
      fetchSettings()
    }
  }, [loading, isAuthenticated, router])

  const fetchSettings = async () => {
    try {
      const response = await fetch('/api/admin/settings', {
        headers: getAuthHeaders()
      })

      if (response.ok) {
        const data = await response.json()
        if (data.settings) {
          setSettings(data.settings)
        }
      }
    } catch (error) {
      console.error('Error fetching settings:', error)
    }
  }

  const fetchDashboardStats = async () => {
    try {
      const response = await fetch('/api/admin/dashboard', {
        headers: getAuthHeaders()
      })

      if (response.ok) {
        const data = await response.json()
        setStats(data)
      } else if (response.status === 401) {
        // Token expired or invalid
        logout()
      }
    } catch (error) {
      console.error('Error fetching dashboard stats:', error)
    }
  }

  const handleLogout = () => {
    logout()
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'PENDING':
        return 'bg-yellow-100 text-yellow-800'
      case 'IN_PROGRESS':
        return 'bg-amber-100 text-amber-800'
      case 'NEED_REVISION':
        return 'bg-orange-100 text-orange-800'
      case 'REVIEWING':
        return 'bg-purple-100 text-purple-800'
      case 'COMPLETED':
        return 'bg-green-100 text-green-800'
      default:
        return 'bg-gray-100 text-gray-800'
    }
  }

  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'PENDING':
        return 'Menunggu Verifikasi'
      case 'IN_PROGRESS':
        return 'Sedang Diproses'
      case 'NEED_REVISION':
        return 'Perlu Revisi'
      case 'REVIEWING':
        return 'Sedang Ditinjau'
      case 'COMPLETED':
        return 'Selesai'
      default:
        return status
    }
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('id-ID', {
      day: 'numeric',
      month: 'short',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-amber-600 mx-auto"></div>
          <p className="mt-2 text-gray-600">Memuat dashboard...</p>
        </div>
      </div>
    )
  }

  return (
    <AdminSidebar user={user}>
      {/* Welcome Section */}
      <div className="mb-8">
        <h2 className="text-2xl font-bold text-gray-900">
          Selamat datang, {user?.name}!
        </h2>
        <p className="text-gray-600">
          Ini adalah dashboard sistem pelayanan digital Polres Wonosobo
        </p>
      </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <Card className="hover:shadow-lg transition-shadow">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">
                Total Pengajuan
              </CardTitle>
              <FileText className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats?.totalRequests || 0}</div>
              <p className="text-xs text-muted-foreground">
                Semua pengajuan
              </p>
            </CardContent>
          </Card>

          <Card className="hover:shadow-lg transition-shadow">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">
                Menunggu Verifikasi
              </CardTitle>
              <Clock className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-yellow-600">
                {stats?.pendingRequests || 0}
              </div>
              <p className="text-xs text-muted-foreground">
                Perlu diproses
              </p>
            </CardContent>
          </Card>

          <Card className="hover:shadow-lg transition-shadow">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">
                Sedang Diproses
              </CardTitle>
              <AlertCircle className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-amber-600">
                {stats?.inProgressRequests || 0}
              </div>
              <p className="text-xs text-muted-foreground">
                Sedang ditangani
              </p>
            </CardContent>
          </Card>

          <Card className="hover:shadow-lg transition-shadow">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">
                Selesai
              </CardTitle>
              <CheckCircle className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-green-600">
                {stats?.completedRequests || 0}
              </div>
              <p className="text-xs text-muted-foreground">
                Selesai diproses
              </p>
            </CardContent>
          </Card>
        </div>

        {/* System Settings Info */}
        <Card className="hover:shadow-lg transition-shadow">
          <CardHeader>
            <div className="flex justify-between items-center">
              <div>
                <CardTitle className="flex items-center gap-2">
                  <Settings className="h-5 w-5" />
                  Informasi Sistem
                </CardTitle>
                <CardDescription>
                  Konfigurasi sistem saat ini
                </CardDescription>
              </div>
              <Button asChild variant="outline">
                <Link href="/admin/settings">Pengaturan</Link>
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            {settings ? (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm font-medium text-gray-700">
                    <Building className="h-4 w-4" />
                    Nama Situs
                  </div>
                  <p className="text-sm text-gray-600">{settings.siteName}</p>
                </div>
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm font-medium text-gray-700">
                    <Mail className="h-4 w-4" />
                    Email Kontak
                  </div>
                  <p className="text-sm text-gray-600">{settings.contactEmail}</p>
                </div>
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm font-medium text-gray-700">
                    <Phone className="h-4 w-4" />
                    Telepon Kontak
                  </div>
                  <p className="text-sm text-gray-600">{settings.contactPhone}</p>
                </div>
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm font-medium text-gray-700">
                    <Globe className="h-4 w-4" />
                    Zona Waktu
                  </div>
                  <p className="text-sm text-gray-600">{settings.timezone}</p>
                </div>
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm font-medium text-gray-700">
                    <Clock className="h-4 w-4" />
                    Jam Operasional
                  </div>
                  <p className="text-sm text-gray-600">{settings.workingHours}</p>
                </div>
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm font-medium text-gray-700">
                    <FileText className="h-4 w-4" />
                    Ukuran File Maksimal
                  </div>
                  <p className="text-sm text-gray-600">{settings.maxFileSize} MB</p>
                </div>
              </div>
            ) : (
              <div className="text-center py-4 text-gray-500">
                <Settings className="h-8 w-8 mx-auto mb-2 opacity-50" />
                <p className="text-sm">Memuat pengaturan sistem...</p>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Recent Requests */}
        <Card className="hover:shadow-lg transition-shadow">
          <CardHeader>
            <div className="flex justify-between items-center">
              <div>
                <CardTitle>Pengajuan Terbaru</CardTitle>
                <CardDescription>
                  5 pengajuan terakhir yang masuk
                </CardDescription>
              </div>
              <Button asChild variant="outline">
                <Link href="/admin/requests">Lihat Semua</Link>
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            {stats?.recentRequests && stats.recentRequests.length > 0 ? (
              <div className="space-y-4">
                {stats.recentRequests.map((request) => (
                  <div key={request.id} className="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50 transition-colors">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-1">
                        <span className="font-medium">{request.trackingNumber}</span>
                        <Badge className={getStatusColor(request.status)}>
                          {getStatusLabel(request.status)}
                        </Badge>
                      </div>
                      <div className="text-sm text-gray-600">
                        {request.service.title} • {request.user.name}
                      </div>
                      <div className="text-xs text-gray-500">
                        {formatDate(request.createdAt)}
                      </div>
                    </div>
                    <Button asChild variant="ghost" size="sm">
                      <Link href={`/admin/requests/${request.id}`}>
                        Detail
                      </Link>
                    </Button>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500">
                <FileText className="h-12 w-12 mx-auto mb-4 opacity-50" />
                <p>Belum ada pengajuan masuk</p>
              </div>
            )}
          </CardContent>
        </Card>
    </AdminSidebar>
  )
}