"use client"

import { useState, useEffect } from "react"
import { FiEdit3, FiInfo, FiPlus, FiTrash } from "react-icons/fi"
import { toast } from "sonner"

import DeleteConfirmationDialog from "@/components/dialogs/DeleteConfirmationDialog"
import { Button } from "@/components/ui/button"
import Pagination from "@/components/common/pagination"
import Table from "@/components/common/Table"
import Tooltip from "@/components/ui/tooltip"
import EmptyState from "@/components/common/EmptyState"
import { useAuth } from "@/context/AuthContext"
import { getTawtheeqContracts, deleteTawtheeqContract, TawtheeqContractListItem } from "@/services/userPanelService"

const STATUS_STYLES: Record<string, string> = {
  paid: "bg-[#F0FDF4] text-[#16A34A]",
  payment_failed: "bg-[#FEF2F2] text-[#DC2626]",
  draft: "bg-[#F1F5F9] text-[#475569]",
  pending: "bg-[#FEF9C3] text-[#A16207]",
  pending_review: "bg-[#FEF9C3] text-[#A16207]",
  property_update_required: "bg-[#EFF6FF] text-[#1D4ED8]",
  approved: "bg-[#F0FDF4] text-[#16A34A]",
  rejected: "bg-[#FEF2F2] text-[#DC2626]",
}

const TYPE_STYLES: Record<string, string> = {
  residential: "bg-[#0092B81A] text-[#0092B8]",
  commercial: "bg-[#4F39F61A] text-[#4F39F6]",
}

const ContractRequestsPage = () => {
  const { token } = useAuth()
  const [contracts, setContracts] = useState<TawtheeqContractListItem[]>([])
  const [loading, setLoading] = useState(true)
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [isDeleting, setIsDeleting] = useState(false)
  const [selectedId, setSelectedId] = useState<number | null>(null)

  useEffect(() => {
    if (!token) { setLoading(false); return }
    getTawtheeqContracts(token).then((data) => {
      setContracts(data)
      setLoading(false)
    })
  }, [token])

  const handleDelete = async () => {
    if (!token || selectedId === null) return

    setIsDeleting(true)
    try {
      const result = await deleteTawtheeqContract(token, selectedId)

      if (result.success) {
        // Optimistic / Immediate UI update
        setContracts((prev) => prev.filter((c) => c.id !== selectedId))
        setDeleteDialogOpen(false)
        toast.success("تم حذف الطلب بنجاح")
      } else {
        if (result.status === 401 || result.status === 403) {
          toast.error("انتهت الجلسة أو ليس لديك صلاحية للحذف. يرجى تسجيل الدخول مرة أخرى.")
        } else {
          toast.error("فشل حذف الطلب. يرجى المحاولة لاحقاً.")
        }
      }
    } catch (error) {
      toast.error("حدث خطأ غير متوقع.")
    } finally {
      setIsDeleting(false)
      setSelectedId(null)
    }
  }

  const columns = [
    {
      key: "title",
      header: "بيانات الطلب",
      thClassName: "w-1/2",
      tdClassName: "py-2 pr-2",
      render: (request: TawtheeqContractListItem) => (
        <div className="flex gap-4">
          <div className="w-15 h-15 rounded-lg overflow-hidden bg-[#F1F5F9] flex items-center justify-center">
            <span className="text-xs text-[#90A1B9]">عقد</span>
          </div>
          <div className="flex flex-col justify-around">
            <p className="font-medium">طلب #{request.requestId}</p>
            <p className="text-[#62748E] text-sm">{request.propertyType || request.typeDisplay}</p>
          </div>
        </div>
      ),
    },
    {
      key: "status",
      header: "حالة الطلب",
      render: (request: TawtheeqContractListItem) => (
        <div className="flex items-center gap-1">
          <span
            className={`flex items-center gap-1 w-fit px-2 py-1 rounded-sm text-sm ${STATUS_STYLES[request.status] || "bg-[#E2E8F0] text-[#475569]"}`}
          >
            {request.statusDisplay}
          </span>
          {request.status === 'payment_failed' && (
            <Tooltip content="فشل الدفع يرجي التحقق من بيانات البطاقة او المحفظة">
              <div className="w-5 h-5 flex items-center justify-center bg-[#DC2626] text-white rounded-full cursor-help">
                <span className="text-xs font-bold font-serif">!</span>
              </div>
            </Tooltip>
          )}
          {request.status === 'property_update_required' && (
            <Tooltip content="يرجي تحديث بيانات العقار لإكمال معالجة الطلب">
              <div className="w-5 h-5 flex items-center justify-center bg-[#1D4ED8] text-white rounded-full cursor-help">
                <span className="text-xs font-bold font-serif">!</span>
              </div>
            </Tooltip>
          )}
        </div>
      ),
    },
    {
      key: "type",
      header: "نوع العقد",
      render: (request: TawtheeqContractListItem) => (
        <span
          className={`inline-flex items-center gap-1 w-fit px-2 py-1 rounded-sm text-sm ${TYPE_STYLES[request.type] || "bg-[#0092B81A] text-[#0092B8]"}`}
        >
          {request.typeDisplay}
        </span>
      ),
    },
    {
      key: "actions",
      header: "الإجراءات",
      tdClassName: "py-2 pl-2",
      render: (request: TawtheeqContractListItem) => (
        <div className="flex justify-center gap-2">
          <Button className="w-8 h-8 bg-[#0525311A] hover:bg-[#0525311A] text-[#05222D] rounded-full font-normal">
            <FiEdit3 strokeWidth={1.8} />
          </Button>
          <Button
            variant="destructive"
            className="w-8 h-8 bg-[#FEF2F2] hover:bg-[#FEF2F2] text-[#E7000B] rounded-full font-normal"
            onClick={() => {
              setSelectedId(request.id)
              setDeleteDialogOpen(true)
            }}
          >
            <FiTrash />
          </Button>
        </div>
      ),
    },
  ]

  if (loading) {
    return (
      <div className="flex-1 flex items-center justify-center py-20">
        <div className="w-8 h-8 border-2 border-[#0092B8] border-t-transparent rounded-full animate-spin" />
      </div>
    )
  }

  return (
    <div className="flex-1 overflow-auto">
      <div className="lg:w-3/4 lg:mx-auto">
        <div className="flex flex-col md:flex-row items-center justify-between mb-4 gap-4">
          <h4 className="text-[#1D293D] text-lg font-medium">طلبات توثيق العقود</h4>
          <Button
            className="font-normal text-base rounded-full bg-[#0525311A]"
            variant="secondary"
          >
            <FiPlus />
            اضافة طلب جديد
          </Button>
        </div>

        {contracts.length > 0 ? (
          <>
            <Table columns={columns} data={contracts} />
            <Pagination
              currentPage={1}
              totalPages={Math.ceil(contracts.length / 10)}
              pageSize={10}
              totalCount={contracts.length}
              onPageChange={() => { }}
            />
          </>
        ) : (
          <EmptyState title="لا توجد طلبات توثيق عقود" description="قم بإضافة طلب جديد لتوثيق عقد" />
        )}
      </div>

      <DeleteConfirmationDialog
        open={deleteDialogOpen}
        onOpenChange={setDeleteDialogOpen}
        onConfirm={handleDelete}
        isLoading={isDeleting}
      />
    </div>
  )
}

export default ContractRequestsPage;