'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { useAuth } from '@/contexts/AuthContext'
import { portalAPI, type PortalProfile } from '@/lib/api/portal'
import LoadingSpinner from '@/components/LoadingSpinner'
import { Banknote, Calendar, ShoppingCart, Clock, Plus, ArrowLeft, CheckCircle2,FileText } from 'lucide-react'
import { toast } from 'react-hot-toast'

export default function PortalDashboardPage() {
  const { hasPermission } = useAuth()
  const [data, setData] = useState<PortalProfile | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    portalAPI.getMe()
      .then(setData)
      .catch(() => toast.error('فشل تحميل البيانات'))
      .finally(() => setLoading(false))
  }, [])

  if (loading) return <LoadingSpinner />
  if (!data) return <div className="text-center text-gray-500 py-12">لا توجد بيانات</div>

  const { employee, stats } = data
  const canViewDepartmentLeaveRequests = hasPermission('department_leave_requests', 'view')
  const canViewDepartmentExpenseClaims = hasPermission('department_expense_claims', 'view')
  const name = employee.firstNameAr && employee.lastNameAr
    ? `${employee.firstNameAr} ${employee.lastNameAr}`
    : `${employee.firstName} ${employee.lastName}`

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">مرحباً، {name}</h1>
        <p className="text-gray-600 mt-1">
          {employee.department?.nameAr || employee.department?.name} - {employee.position?.titleAr || employee.position?.title}
        </p>
      </div>

      <div className={`grid grid-cols-1 md:grid-cols-2 ${canViewDepartmentLeaveRequests ? 'lg:grid-cols-5' : 'lg:grid-cols-4'} gap-6`}>
        <div className="bg-white rounded-xl shadow p-6 border border-gray-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-600">رصيد الإجازات</p>
              <p className="text-2xl font-bold text-teal-600 mt-1">
                {stats.leaveBalance.reduce((s, b) => s + b.available, 0)} يوم
              </p>
            </div>
            <div className="bg-teal-100 p-3 rounded-lg">
              <Calendar className="h-6 w-6 text-teal-600" />
            </div>
          </div>
          <Link href="/portal/leave" className="mt-4 text-sm text-teal-600 hover:underline flex items-center gap-1">
            عرض التفاصيل <ArrowLeft className="h-4 w-4" />
          </Link>
        </div>

        {canViewDepartmentLeaveRequests && (
          <div className="bg-white rounded-xl shadow p-6 border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">طلبات إجازات القسم</p>
                <p className="text-sm text-gray-500 mt-1">مراجعة واعتماد</p>
              </div>
              <div className="bg-emerald-100 p-3 rounded-lg">
                <CheckCircle2 className="h-6 w-6 text-emerald-600" />
              </div>
            </div>
            <Link href="/portal/managed-leaves" className="mt-4 text-sm text-emerald-600 hover:underline flex items-center gap-1">
              عرض الطلبات <ArrowLeft className="h-4 w-4" />
            </Link>
          </div>
        )}

        <div className="bg-white rounded-xl shadow p-6 border border-gray-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-600">القروض النشطة</p>
              <p className="text-2xl font-bold text-amber-600 mt-1">{stats.activeLoansCount}</p>
            </div>
            <div className="bg-amber-100 p-3 rounded-lg">
              <Banknote className="h-6 w-6 text-amber-600" />
            </div>
          </div>
          <Link href="/portal/loans" className="mt-4 text-sm text-amber-600 hover:underline flex items-center gap-1">
            عرض القروض <ArrowLeft className="h-4 w-4" />
          </Link>
        </div>

        <div className="bg-white rounded-xl shadow p-6 border border-gray-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-600">كشوف المصاريف المعلقة</p>
              <p className="text-2xl font-bold text-fuchsia-600 mt-1">{stats.pendingExpenseClaimsCount}</p>
            </div>
            <div className="bg-fuchsia-100 p-3 rounded-lg">
              <FileText className="h-6 w-6 text-fuchsia-600" />
            </div>
          </div>
          <Link href="/portal/expense-claims" className="mt-4 text-sm text-fuchsia-600 hover:underline flex items-center gap-1">
            عرض الكشوف <ArrowLeft className="h-4 w-4" />
          </Link>
        </div>

        <div className="bg-white rounded-xl shadow p-6 border border-gray-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-600">طلبات قيد المراجعة</p>
              <p className="text-2xl font-bold text-blue-600 mt-1">
                {stats.pendingLeavesCount + stats.pendingPurchaseRequestsCount + stats.pendingExpenseClaimsCount}
              </p>
            </div>
            <div className="bg-blue-100 p-3 rounded-lg">
              <ShoppingCart className="h-6 w-6 text-blue-600" />
            </div>
          </div>
          <div className="mt-4 flex gap-4">
            <Link href="/portal/leave" className="text-sm text-blue-600 hover:underline">الإجازات</Link>
            <Link href="/portal/purchase-requests" className="text-sm text-blue-600 hover:underline">الشراء</Link>
            <Link href="/portal/expense-claims" className="text-sm text-blue-600 hover:underline">المصاريف</Link>
          </div>
        </div>

        <div className="bg-white rounded-xl shadow p-6 border border-gray-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-600">حضوري</p>
              <p className="text-sm text-gray-500 mt-1">هذا الشهر</p>
            </div>
            <div className="bg-gray-100 p-3 rounded-lg">
              <Clock className="h-6 w-6 text-gray-600" />
            </div>
          </div>
          <Link href="/portal/attendance" className="mt-4 text-sm text-gray-600 hover:underline flex items-center gap-1">
            عرض الحضور <ArrowLeft className="h-4 w-4" />
          </Link>
        </div>
      </div>

      {stats.leaveBalance.length > 0 && (
        <div className="bg-white rounded-xl shadow p-6 border border-gray-100">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">تفاصيل رصيد الإجازات</h2>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b">
                  <th className="text-right py-2">نوع الإجازة</th>
                  <th className="text-right py-2">الإجمالي</th>
                  <th className="text-right py-2">المستخدم</th>
                  <th className="text-right py-2">المتبقي</th>
                </tr>
              </thead>
              <tbody>
                {stats.leaveBalance.map((b) => (
                  <tr key={b.leaveType} className="border-b last:border-0">
                    <td className="py-2">
                      {b.leaveType === 'ANNUAL' ? 'سنوية' : b.leaveType === 'HOURLY' ? 'ساعية' : b.leaveType}
                    </td>
                    <td className="py-2">{b.totalDays + b.carriedOver}</td>
                    <td className="py-2">{b.usedDays}</td>
                    <td className="py-2 font-semibold text-teal-600">{b.available}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      <div className="flex flex-wrap gap-4">
        <Link href="/portal/loans" className="inline-flex items-center gap-2 px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700">
          <Plus className="h-4 w-4" />
          طلب قرض
        </Link>

        <Link href="/portal/leave" className="inline-flex items-center gap-2 px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700">
          <Plus className="h-4 w-4" />
          طلب إجازة
        </Link>

        {canViewDepartmentLeaveRequests && (
          <Link href="/portal/managed-leaves" className="inline-flex items-center gap-2 px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700">
            <CheckCircle2 className="h-4 w-4" />
            طلبات إجازات القسم
          </Link>
        )}

        <Link href="/portal/expense-claims" className="inline-flex items-center gap-2 px-4 py-2 bg-fuchsia-600 text-white rounded-lg hover:bg-fuchsia-700">
          <Plus className="h-4 w-4" />
          كشف مصاريف
        </Link>

        <Link href="/portal/purchase-requests" className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
          <Plus className="h-4 w-4" />
          طلب شراء
        </Link>
      </div>
    </div>
  )
}