'use client'

import { useState, useEffect } from 'react'
import { portalAPI, type Loan } from '@/lib/api/portal'
import Modal from '@/components/Modal'
import LoadingSpinner from '@/components/LoadingSpinner'
import { toast } from 'react-hot-toast'
import { Banknote, Plus, ChevronLeft } from 'lucide-react'

const STATUS_MAP: Record<string, { label: string; color: string }> = {
  PENDING_HR: { label: 'بانتظار موافقة الموارد البشرية', color: 'bg-amber-100 text-amber-800' },
  PENDING_ADMIN: { label: 'بانتظار موافقة مدير النظام', color: 'bg-orange-100 text-orange-800' },
  REJECTED: { label: 'مرفوض', color: 'bg-red-100 text-red-800' },
  ACTIVE: { label: 'نشط', color: 'bg-blue-100 text-blue-800' },
  PAID_OFF: { label: 'مسدد', color: 'bg-gray-100 text-gray-800' },
}

export default function PortalLoansPage() {
  const [loans, setLoans] = useState<Loan[]>([])
  const [loading, setLoading] = useState(true)
  const [showModal, setShowModal] = useState(false)
  const [submitting, setSubmitting] = useState(false)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [form, setForm] = useState({ type: 'SALARY_ADVANCE', amount: '', installments: '1', reason: '' })

  useEffect(() => {
    portalAPI.getLoans()
      .then(setLoans)
      .catch(() => toast.error('فشل تحميل القروض'))
      .finally(() => setLoading(false))
  }, [])

  const resetForm = () => {
    setForm({ type: 'SALARY_ADVANCE', amount: '', installments: '1', reason: '' })
    setEditingId(null)
  }

  const openEdit = (loan: Loan) => {
    setEditingId(loan.id)
    setForm({
      type: loan.type,
      amount: String(loan.amount ?? ''),
      installments: String(loan.installments ?? '1'),
      reason: loan.reason || '',
    })
    setShowModal(true)
  }

  const handleDelete = async (id: string) => {
    if (!confirm('حذف طلب القرض؟')) return
    try {
      await portalAPI.deleteLoanRequest(id)
      toast.success('تم الحذف')
      setLoans((prev) => prev.filter((l) => l.id !== id))
    } catch (err: any) {
      toast.error(err?.response?.data?.message || 'فشل الحذف')
    }
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    const amount = parseFloat(form.amount)

    if (!amount || amount <= 0) {
      toast.error('أدخل مبلغاً صالحاً')
      return
    }

    if (!form.reason.trim()) {
      toast.error('سبب القرض مطلوب')
      return
    }

    setSubmitting(true)
    const payload = {
      type: form.type,
      amount,
      installments: parseInt(form.installments) || 1,
      reason: form.reason.trim(),
    }
    const action = editingId
      ? portalAPI.updateLoanRequest(editingId, payload)
      : portalAPI.submitLoanRequest(payload)
    action
      .then((loan) => {
        if (editingId) {
          setLoans((prev) => prev.map((l) => (l.id === editingId ? loan : l)))
        } else {
          setLoans((prev) => [loan, ...prev])
        }
        setShowModal(false)
        resetForm()
        toast.success(editingId ? 'تم تعديل الطلب' : 'تم إرسال طلب القرض')
      })
      .catch((err: any) => toast.error(err?.response?.data?.message || 'فشل إرسال الطلب'))
      .finally(() => setSubmitting(false))
  }

  if (loading) return <LoadingSpinner />

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900">قروضي</h1>
        <button
          onClick={() => { resetForm(); setShowModal(true) }}
          className="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" />
          طلب قرض
        </button>
      </div>

      {loans.length === 0 ? (
        <div className="bg-white rounded-xl shadow p-12 text-center text-gray-500">
          <Banknote className="h-12 w-12 mx-auto mb-4 text-gray-300" />
          <p>لا توجد قروض</p>
          <button onClick={() => setShowModal(true)} className="mt-4 text-teal-600 hover:underline">
            تقديم طلب قرض
          </button>
        </div>
      ) : (
        <div className="space-y-4">
          {loans.map((loan) => {
            const statusInfo = STATUS_MAP[loan.status] || { label: loan.status, color: 'bg-gray-100 text-gray-800' }
            return (
              <div key={loan.id} className="bg-white rounded-xl shadow p-6 border border-gray-100">
                <div className="flex justify-between items-start">
                  <div>
                    <p className="font-semibold text-gray-900">{loan.loanNumber}</p>
                    <p className="text-sm text-gray-600 mt-1">
                      {loan.type === 'SALARY_ADVANCE' ? 'سلفة راتب' : loan.type} - {Number(loan.amount).toLocaleString()} ر.س
                    </p>
                    <p className="text-xs text-gray-500 mt-1">
                      {loan.installments} أقساط × {loan.monthlyAmount ? Number(loan.monthlyAmount).toLocaleString() : '-'} ر.س
                    </p>
                    {loan.installmentsList && loan.installmentsList.length > 0 && (
                      <div className="mt-3 flex flex-wrap gap-2">
                        {loan.installmentsList.map((i) => (
                          <span
                            key={i.id}
                            className={`text-xs px-2 py-1 rounded ${
                              i.status === 'PAID' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'
                            }`}
                          >
                            {i.installmentNumber}: {i.status === 'PAID' ? 'مسدد' : 'معلق'}
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                  <div className="flex flex-col items-end gap-2">
                    <span className={`px-3 py-1 rounded-full text-xs font-medium ${statusInfo.color}`}>
                      {statusInfo.label}
                    </span>
                    {loan.status === 'PENDING_HR' && (
                      <div className="flex gap-2">
                        <button type="button" onClick={() => openEdit(loan)} className="text-xs text-teal-600 hover:underline">تعديل</button>
                        <button type="button" onClick={() => handleDelete(loan.id)} className="text-xs text-red-600 hover:underline">حذف</button>
                      </div>
                    )}
                  </div>
                </div>
                {loan.rejectedReason && (
                  <p className="mt-2 text-sm text-red-600">سبب الرفض: {loan.rejectedReason}</p>
                )}
              </div>
            )
          })}
        </div>
      )}

      <Modal
        isOpen={showModal}
        onClose={() => { setShowModal(false); resetForm() }}
        title={editingId ? 'تعديل طلب القرض' : 'طلب قرض جديد'}
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">نوع القرض</label>
            <select
              value={form.type}
              onChange={(e) => setForm((p) => ({ ...p, type: e.target.value }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg"
            >
              <option value="SALARY_ADVANCE">سلفة راتب</option>
              <option value="EQUIPMENT">معدات</option>
              <option value="PERSONAL">شخصي</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">المبلغ (ر.س) *</label>
            <input
              type="number"
              min="1"
              step="0.01"
              value={form.amount}
              onChange={(e) => setForm((p) => ({ ...p, amount: e.target.value }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg"
              required
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">عدد الأقساط</label>
            <input
              type="number"
              min="1"
              value={form.installments}
              onChange={(e) => setForm((p) => ({ ...p, installments: e.target.value }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">السبب</label>
            <textarea
              value={form.reason}
              onChange={(e) => setForm((p) => ({ ...p, reason: e.target.value }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg"
              rows={3}
              required
            />
          </div>
          <div className="flex justify-end gap-2">
            <button type="button" onClick={() => setShowModal(false)} className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg">
              إلغاء
            </button>
            <button type="submit" disabled={submitting} className="px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50">
              {submitting ? 'جاري الإرسال...' : (editingId ? 'حفظ التعديل' : 'إرسال الطلب')}
            </button>
          </div>
        </form>
      </Modal>
    </div>
  )
}
