'use client';

import { useEffect, useMemo, useState } from 'react';
import { portalAPI, type ExpenseClaim } from '@/lib/api/portal';
import Modal from '@/components/Modal';
import { useSearchParams } from 'next/navigation';

type ExpenseClaimLine = {
  expenseDate: string;
  amount: string;
  entityName: string;
  description: string;
  projectOrTender: string;
  proofRef: string;
};

type ExpenseClaimFormState = {
  items: ExpenseClaimLine[];
  description: string;
  attachments: File[];
};

const emptyLine = (): ExpenseClaimLine => ({
  expenseDate: '',
  amount: '',
  entityName: '',
  description: '',
  projectOrTender: '',
  proofRef: '',
});

const initialForm: ExpenseClaimFormState = {
  items: [emptyLine()],
  description: '',
  attachments: [],
};

function getStatusLabel(status: string) {
  switch (status) {
    case 'PENDING':
      return 'قيد المراجعة';
    case 'APPROVED':
      return 'مقبول';
    case 'REJECTED':
      return 'مرفوض';
    default:
      return status;
  }
}

function getStatusClasses(status: string) {
  switch (status) {
    case 'PENDING':
      return 'bg-yellow-100 text-yellow-800';
    case 'APPROVED':
      return 'bg-green-100 text-green-800';
    case 'REJECTED':
      return 'bg-red-100 text-red-800';
    default:
      return 'bg-gray-100 text-gray-700';
  }
}

function formatDate(value?: string | null) {
  if (!value) return '-';
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return value;
  return d.toLocaleDateString('en-CA');
}

export default function PortalExpenseClaimsPage() {
  const [claims, setClaims] = useState<ExpenseClaim[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [form, setForm] = useState<ExpenseClaimFormState>(initialForm);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [removeAttachmentIds, setRemoveAttachmentIds] = useState<string[]>([]);
  const [existingAttachments, setExistingAttachments] = useState<
    Array<{ id: string; originalName?: string; mimeType?: string }>
  >([]);

  const [statusFilter, setStatusFilter] = useState('all');
  const [paidFilter, setPaidFilter] = useState<'all' | 'paid' | 'unpaid'>('all');
  const filteredClaims = useMemo(() => {
    return claims.filter((claim) => {
      if (statusFilter !== 'all' && claim.status !== statusFilter) return false;
      if (paidFilter === 'paid' && !claim.isPaid) return false;
      if (paidFilter === 'unpaid' && claim.isPaid) return false;
      return true;
    });
  }, [claims, statusFilter, paidFilter]);

  const totalAmount = useMemo(() => {
    return form.items.reduce((sum, item) => sum + Number(item.amount || 0), 0);
  }, [form.items]);

  async function loadClaims() {
    try {
      setLoading(true);
      setError(null);
      const data = await portalAPI.getExpenseClaims();
      setClaims(data);
    } catch (err: any) {
      setError(err?.response?.data?.message || 'تعذر تحميل كشوف المصاريف');
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    loadClaims();
  }, []);

  const addItem = () => {
    setForm((prev) => ({
      ...prev,
      items: [...prev.items, emptyLine()],
    }));
  };

  const removeItem = (index: number) => {
    setForm((prev) => ({
      ...prev,
      items: prev.items.filter((_, i) => i !== index),
    }));
  };

  const updateItem = (
    index: number,
    key: keyof ExpenseClaimLine,
    value: string
  ) => {
    setForm((prev) => ({
      ...prev,
      items: prev.items.map((item, i) =>
        i === index ? { ...item, [key]: value } : item
      ),
    }));
  };

  const resetForm = () => {
    setForm(initialForm);
    setEditingId(null);
    setRemoveAttachmentIds([]);
    setExistingAttachments([]);
  };

  const openEdit = (claim: ExpenseClaim) => {
    setEditingId(claim.id);
    const items = Array.isArray(claim.items) && claim.items.length > 0
      ? claim.items.map((it: any) => ({
          expenseDate: it.expenseDate ? String(it.expenseDate).split('T')[0] : '',
          amount: String(it.amount ?? ''),
          entityName: it.entityName || '',
          description: it.description || '',
          projectOrTender: it.projectOrTender || '',
          proofRef: it.proofRef || '',
        }))
      : [emptyLine()];
    setForm({
      items,
      description: claim.description || '',
      attachments: [],
    });
    setExistingAttachments(
      (claim.attachments || []).map((a) => ({
        id: a.id,
        originalName: a.originalName,
        mimeType: a.mimeType,
      }))
    );
    setRemoveAttachmentIds([]);
    setShowModal(true);
  };

  const handleDelete = async (id: string) => {
    if (!confirm('حذف كشف المصاريف؟')) return;
    try {
      await portalAPI.deleteExpenseClaim(id);
      setClaims((prev) => prev.filter((c) => c.id !== id));
    } catch (err: any) {
      alert(err?.response?.data?.message || 'فشل الحذف');
    }
  };


  async function openAttachment(attachment: any) {
  try {
    const blob = await portalAPI.viewExpenseClaimAttachment(attachment.id);
    const blobUrl = window.URL.createObjectURL(
      new Blob([blob], { type: attachment.mimeType })
    );

    window.open(blobUrl, '_blank');

    setTimeout(() => {
      window.URL.revokeObjectURL(blobUrl);
    }, 10000);
  } catch (error) {
    alert('تعذر فتح المرفق');
  }
}

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();

    const items = form.items
      .map((item) => ({
        expenseDate: item.expenseDate,
        amount: Number(item.amount || 0),
        entityName: item.entityName.trim() || undefined,
        description: item.description.trim(),
        projectOrTender: item.projectOrTender.trim() || undefined,
        proofRef: item.proofRef.trim() || undefined,
      }))
      .filter(
        (item) =>
          item.expenseDate &&
          item.description &&
          Number(item.amount) > 0
      );

    if (items.length === 0) {
      alert('يرجى إضافة بند واحد على الأقل مع التاريخ والمبلغ والبيان');
      return;
    }

    try {
      setSubmitting(true);

      if (editingId) {
        await portalAPI.updateExpenseClaim(editingId, {
          items,
          description: form.description.trim() || undefined,
          attachments: form.attachments,
          removeAttachmentIds,
        });
      } else {
        await portalAPI.submitExpenseClaim({
          items,
          description: form.description.trim() || undefined,
          attachments: form.attachments,
        });
      }

      resetForm();
      setShowModal(false);
      await loadClaims();
    } catch (err: any) {
      alert(err?.response?.data?.message || 'تعذر إرسال طلب كشف المصاريف');
    } finally {
      setSubmitting(false);
    }
  }

  const searchParams = useSearchParams();
  const claimId = searchParams.get('claimId');

  return (
    <div className="space-y-6" dir="rtl">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">كشف المصاريف</h1>
          <p className="text-sm text-gray-500 mt-1">
            يمكنك تقديم كشف مصاريف جديد ومتابعة حالة الطلبات السابقة
          </p>
        </div>

        <button
          onClick={() => { resetForm(); setShowModal(true); }}
          className="inline-flex items-center rounded-lg bg-teal-600 px-4 py-2 text-sm font-medium text-white hover:bg-teal-700"
        >
          + طلب كشف مصاريف
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="rounded-xl border bg-white p-5 shadow-sm">
          <div className="text-sm text-gray-500">إجمالي الطلبات</div>
          <div className="mt-2 text-2xl font-bold text-gray-900">
            {claims.length}
          </div>
        </div>

        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="rounded-lg border border-gray-300 px-3 py-2 text-sm"
        >
          <option value="all">الكل</option>
          <option value="PENDING">قيد المراجعة</option>
          <option value="APPROVED">مقبول</option>
          <option value="REJECTED">مرفوض</option>
        </select>

        <select
          value={paidFilter}
          onChange={(e) => setPaidFilter(e.target.value as 'all' | 'paid' | 'unpaid')}
          className="rounded-lg border border-gray-300 px-3 py-2 text-sm"
        >
          <option value="all">القبض: الكل</option>
          <option value="paid">مقبوض</option>
          <option value="unpaid">غير مقبوض</option>
        </select>

        <div className="rounded-xl border bg-white p-5 shadow-sm">
          <div className="text-sm text-gray-500">آخر تحديث</div>
          <div className="mt-2 text-base font-semibold text-gray-900">
            {claims[0]?.updatedAt ? formatDate(claims[0].updatedAt) : '-'}
          </div>
        </div>
      </div>

      <div className="rounded-xl border bg-white shadow-sm">
        <div className="border-b px-5 py-4">
          <h2 className="text-lg font-semibold text-gray-900">طلباتي</h2>
        </div>

        {loading ? (
          <div className="p-6 text-sm text-gray-500">جاري التحميل...</div>
        ) : error ? (
          <div className="p-6 text-sm text-red-600">{error}</div>
        ) : filteredClaims.length === 0 ? (
            <div className="p-6 text-sm text-gray-500">
            لا توجد طلبات كشف مصاريف حالياً
          </div>
        ) : (
          <div className="divide-y">
            {filteredClaims.map((claim) => {
                const isSelected = claim.id === claimId;

              return (
                <div
                  key={claim.id}
                  className={`p-5 ${
                    isSelected ? 'bg-yellow-50 ring-2 ring-yellow-300 rounded-lg' : ''
                  }`}
                >
                  <div className="flex items-start justify-between gap-4 flex-wrap">
                    <div className="space-y-2 w-full">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="text-base font-bold text-gray-900">
                          {claim.claimNumber}
                        </span>
                        <span
                          className={`inline-flex rounded-full px-3 py-1 text-xs font-medium ${getStatusClasses(
                            claim.status
                          )}`}
                        >

                          {getStatusLabel(claim.status)}
                        </span>
                        {claim.status === 'PENDING' && (
                          <span className="inline-flex gap-2">
                            <button
                              type="button"
                              onClick={() => openEdit(claim)}
                              className="text-xs text-teal-600 hover:underline"
                            >
                              تعديل
                            </button>
                            <button
                              type="button"
                              onClick={() => handleDelete(claim.id)}
                              className="text-xs text-red-600 hover:underline"
                            >
                              حذف
                            </button>
                          </span>
                        )}
                      </div>
                      {claim.status === 'APPROVED' && claim.approvalNote ? (
                            <div className="rounded-lg bg-green-50 px-3 py-2 text-sm text-green-700">
                              <span className="font-medium">ملاحظة المعتمِد:</span> {claim.approvalNote}
                            </div>
                          ) : null}

                      {claim.status === 'APPROVED' ? (
                        <div
                          className={`flex items-center gap-3 rounded-lg border px-3 py-2 text-sm ${
                            claim.isPaid
                              ? 'border-emerald-200 bg-emerald-50 text-emerald-800'
                              : 'border-gray-200 bg-gray-50 text-gray-700'
                          }`}
                        >
                          <input
                            type="checkbox"
                            checked={Boolean(claim.isPaid)}
                            disabled
                            readOnly
                            className="h-4 w-4 cursor-not-allowed accent-emerald-600"
                          />
                          <span className="font-medium">
                            {claim.isPaid ? 'مقبوض - تم الدفع' : 'غير مقبوض'}
                          </span>
                        </div>
                      ) : null}

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-2 text-sm text-gray-600">
                        <div>
                          <span className="font-medium text-gray-800">
                            إجمالي المبلغ:
                          </span>{' '}
                          {claim.totalAmount ?? claim.amount ?? '-'}
                        </div>

                        <div>
                          <span className="font-medium text-gray-800">
                            تاريخ الإنشاء:
                          </span>{' '}
                          {formatDate(claim.createdAt)}
                        </div>

                        <div>
                          <span className="font-medium text-gray-800">
                            عدد البنود:
                          </span>{' '}
                          {Array.isArray(claim.items)
                            ? claim.items.length
                            : claim.description
                            ? 1
                            : 0}
                        </div>

                        <div>
                          <span className="font-medium text-gray-800">
                            آخر تحديث:
                          </span>{' '}
                          {formatDate(claim.updatedAt)}
                        </div>
                      </div>

                      {claim.description ? (
                        <div className="text-sm text-gray-700">
                          <span className="font-medium text-gray-800">
                            ملاحظات عامة:
                          </span>{' '}
                          {claim.description}
                        </div>
                      ) : null}

                      {Array.isArray(claim.items) && claim.items.length > 0 ? (
                        <div className="mt-3 space-y-2">
                          <div className="text-sm font-medium text-gray-800">
                            البنود:
                          </div>

                          <div className="space-y-2">
                            {claim.items.map((item: any, idx: number) => (
                              <div
                                key={idx}
                                className="rounded-lg border bg-gray-50 p-3 text-sm text-gray-700"
                              >
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                                  <div>
                                    <span className="font-medium">التاريخ:</span>{' '}
                                    {formatDate(item.expenseDate)}
                                  </div>
                                  <div>
                                    <span className="font-medium">المبلغ:</span>{' '}
                                    {item.amount ?? '-'}
                                  </div>
                                  <div>
                                    <span className="font-medium">اسم الجهة:</span>{' '}
                                    {item.entityName || '-'}
                                  </div>
                                  <div>
                                    <span className="font-medium">
                                      المشروع / المناقصة:
                                    </span>{' '}
                                    {item.projectOrTender || '-'}
                                  </div>
                                  <div className="md:col-span-2">
                                    <span className="font-medium">
                                      الأوراق المثبتة:
                                    </span>{' '}
                                    {item.proofRef || '-'}
                                  </div>
                                  {claim.attachments && claim.attachments.length > 0 ? (
                                    <div className="mt-3 space-y-2">
                                      <div className="text-sm font-medium text-gray-800">المرفقات:</div>

                                      <div className="space-y-1">
                                        {claim.attachments.map((attachment) => (
                                          <button
                                            key={attachment.id}
                                            type="button"
                                            onClick={() => openAttachment(attachment)}
                                            className="block w-full text-right rounded-lg border bg-white px-3 py-2 text-sm text-blue-600 hover:underline"
                                          >
                                            {attachment.originalName}
                                          </button>
                                        ))}
                                      </div>
                                    </div>
                                  ) : null}
                                  <div className="md:col-span-2">
                                    <span className="font-medium">البيان:</span>{' '}
                                    {item.description || '-'}
                                  </div>
                                </div>
                              </div>
                            ))}
                          </div>
                        </div>
                      ) : (
                        <div className="mt-3 rounded-lg border bg-gray-50 p-3 text-sm text-gray-700">
                          <div>
                            <span className="font-medium">تاريخ المصروف:</span>{' '}
                            {formatDate(claim.expenseDate)}
                          </div>
                          <div>
                            <span className="font-medium">المبلغ:</span>{' '}
                            {claim.amount ?? '-'}
                          </div>
                          <div>
                            <span className="font-medium">
                              المشروع / المناقصة:
                            </span>{' '}
                            {claim.projectOrTender || '-'}
                          </div>
                          <div>
                            <span className="font-medium">البيان:</span>{' '}
                            {claim.description || '-'}
                          </div>
                        </div>
                      )}

                      {claim.status === 'REJECTED' && claim.rejectedReason ? (
                        <div className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">
                          <span className="font-medium">سبب الرفض:</span>{' '}
                          {claim.rejectedReason}
                        </div>
                      ) : null}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      <Modal
        isOpen={showModal}
        onClose={() => { setShowModal(false); resetForm(); }}
        title={editingId ? 'تعديل كشف المصاريف' : 'كشف مصاريف جديد'}
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <div className="flex justify-between items-center mb-2">
              <label className="text-sm font-medium text-gray-700">
                بنود كشف المصاريف
              </label>

              <button
                type="button"
                onClick={addItem}
                className="text-teal-600 text-sm hover:underline"
              >
                + إضافة بند
              </button>
            </div>

            <div className="space-y-3">
              {form.items.map((item, index) => (
                <div key={index} className="border rounded-lg p-3 space-y-3">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div>
                      <label className="mb-1 block text-sm font-medium text-gray-700">
                        تاريخ المصروف
                      </label>
                      <input
                        type="date"
                        value={item.expenseDate}
                        onChange={(e) =>
                          updateItem(index, 'expenseDate', e.target.value)
                        }
                        className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm"
                      />
                    </div>

                    <div>
                      <label className="mb-1 block text-sm font-medium text-gray-700">
                        المبلغ
                      </label>
                      <input
                        type="number"
                        min="0"
                        step="0.01"
                        placeholder="المبلغ"
                        value={item.amount}
                        onChange={(e) =>
                          updateItem(index, 'amount', e.target.value)
                        }
                        className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm"
                      />
                    </div>

                    <div>
                      <label className="mb-1 block text-sm font-medium text-gray-700">
                        اسم الجهة
                      </label>
                      <input
                        type="text"
                        placeholder="اسم الجهة"
                        value={item.entityName}
                        onChange={(e) =>
                          updateItem(index, 'entityName', e.target.value)
                        }
                        className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm"
                      />
                    </div>

                    <div>
                      <label className="mb-1 block text-sm font-medium text-gray-700">
                        المشروع / المناقصة
                      </label>
                      <input
                        type="text"
                        placeholder="المشروع / المناقصة"
                        value={item.projectOrTender}
                        onChange={(e) =>
                          updateItem(index, 'projectOrTender', e.target.value)
                        }
                        className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm"
                      />
                    </div>

                    <div className="md:col-span-2">
                      <label className="mb-1 block text-sm font-medium text-gray-700">
                        البيان
                      </label>
                      <textarea
                        placeholder="البيان"
                        value={item.description}
                        onChange={(e) =>
                          updateItem(index, 'description', e.target.value)
                        }
                        className="min-h-[90px] w-full rounded-lg border border-gray-300 px-3 py-2 text-sm"
                      />
                    </div>
                  </div>

                  {form.items.length > 1 && (
                    <div className="flex justify-end">
                      <button
                        type="button"
                        onClick={() => removeItem(index)}
                        className="text-sm text-red-600 hover:underline"
                      >
                        حذف البند
                      </button>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>

          <div>
            <label className="mb-1 block text-sm font-medium text-gray-700">
              ملاحظات عامة
            </label>
            <textarea
              value={form.description}
              onChange={(e) =>
                setForm((prev) => ({ ...prev, description: e.target.value }))
              }
              className="min-h-[100px] w-full rounded-lg border border-gray-300 px-3 py-2 text-sm"
              placeholder="أي ملاحظات عامة على الكشف"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-gray-700">
              المرفقات
            </label>

            {editingId && existingAttachments.length > 0 && (
              <div className="mb-2 space-y-1">
                <div className="text-xs text-gray-500">المرفقات الحالية:</div>
                {existingAttachments.map((a) => {
                  const isRemoved = removeAttachmentIds.includes(a.id);
                  return (
                    <div
                      key={a.id}
                      className={`flex items-center justify-between rounded-lg border px-3 py-2 text-sm ${
                        isRemoved ? 'bg-red-50 border-red-200 text-red-600 line-through' : 'bg-gray-50 text-gray-700'
                      }`}
                    >
                      <span className="truncate">{a.originalName || a.id}</span>
                      <button
                        type="button"
                        onClick={() => {
                          setRemoveAttachmentIds((prev) =>
                            isRemoved ? prev.filter((id) => id !== a.id) : [...prev, a.id]
                          );
                        }}
                        className="text-red-600 hover:underline shrink-0 ms-2"
                      >
                        {isRemoved ? 'استرجاع' : 'إزالة'}
                      </button>
                    </div>
                  );
                })}
              </div>
            )}

            <input
              type="file"
              multiple
              accept="image/*,application/pdf"
              onChange={(e) => {
                const picked = Array.from(e.target.files || []);
                if (picked.length === 0) return;

                setForm((prev) => {
                  const combined = [...prev.attachments, ...picked];
                  if (combined.length > 10) {
                    alert('يمكن إرفاق 10 ملفات كحد أقصى');
                    return { ...prev, attachments: combined.slice(0, 10) };
                  }
                  return { ...prev, attachments: combined };
                });

                // Reset the input so picking the same file again still fires onChange.
                e.target.value = '';
              }}
              className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm"
            />

            <p className="mt-1 text-xs text-gray-500">
              يمكن اختيار أكثر من ملف (حتى 10 ملفات).
            </p>

            {form.attachments.length > 0 ? (
              <div className="mt-2 space-y-1">
                {form.attachments.map((file, idx) => (
                  <div
                    key={`${file.name}-${idx}`}
                    className="flex items-center justify-between rounded-lg bg-gray-50 border px-3 py-2 text-sm text-gray-700"
                  >
                    <span className="truncate">{file.name}</span>
                    <button
                      type="button"
                      onClick={() =>
                        setForm((prev) => ({
                          ...prev,
                          attachments: prev.attachments.filter((_, i) => i !== idx),
                        }))
                      }
                      className="text-red-600 hover:underline shrink-0 ms-2"
                    >
                      إزالة
                    </button>
                  </div>
                ))}
              </div>
            ) : null}
          </div>       

          <div className="rounded-lg bg-gray-50 border px-4 py-3 text-sm font-medium text-gray-700">
            الإجمالي: {totalAmount.toLocaleString()}
          </div>

          <div className="flex items-center justify-end gap-2 pt-2">
            <button
              type="button"
              onClick={() => { setShowModal(false); resetForm(); }}
              className="rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
            >
              إلغاء
            </button>

            <button
              type="submit"
              disabled={submitting}
              className="rounded-lg bg-teal-600 px-4 py-2 text-sm font-medium text-white hover:bg-teal-700 disabled:cursor-not-allowed disabled:opacity-60"
            >
              {submitting ? 'جارٍ الإرسال...' : (editingId ? 'حفظ التعديل' : 'إرسال الطلب')}
            </button>
          </div>
        </form>
      </Modal>
    </div>
  );
}