'use client'

import React, { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Badge, Button, Card, Tooltip } from 'flowbite-react'
import { IoIosArrowRoundBack } from 'react-icons/io'
import Link from 'next/link'
import { FiCheck, FiFile, FiHelpCircle, FiLoader, FiX } from 'react-icons/fi'
import { toast } from 'react-toastify'

import { useAuth } from '@/lib/context/AuthContext'
import { capitalizeWords } from '@/lib/utils/string'
import { handleApiError } from '@/lib/utils/error-handler'
import * as withdrawalServices from '@/lib/services/withdrawal-services'
import FullPageLoader from '@/lib/components/FullPageLoader'
import ConfirmationModal from '@/lib/components/modals/ConfirmationModal'
import { formatIDR } from '@/lib/utils/currency'
import buttonTheme from '@/lib/themes/button'
import { PartnerCategory, PayoutMethod } from '@/lib/types/enums/partner'
import TransferProofModal from '../partials/TransferProofModal'
import CompleteWithdrawalModal from '../partials/CompleteWithdrawalModal'
import RejectWithdrawalModal from '../partials/RejectWithdrawalModal'
import { Withdrawal } from '../types'
import {
  CompleteWithdrawalFormValues,
  RejectWithdrawalFormValues,
} from '../schemas'
import { useWithdrawalBroadcast } from '@/lib/hooks/useWithdrawalBroadcast'

interface MainContentProps {
  withdrawalId: string
}

export default function MainContent({ withdrawalId }: MainContentProps) {
  const router = useRouter()
  const { user } = useAuth()
  const [isLoading, setIsLoading] = useState(true)
  const [withdrawal, setWithdrawal] = useState<Withdrawal | null>(null)
  const [transferProofModal, setTransferProofModal] = useState<ModalState>({
    type: 'view',
    isOpened: false,
  })
  const [confirmationModal, setConfirmationModal] = useState({
    isOpen: false,
    loading: false,
  })
  const [completeModal, setCompleteModal] = useState({
    isOpen: false,
    loading: false,
  })
  const [rejectModal, setRejectModal] = useState({
    isOpen: false,
    loading: false,
  })

  useEffect(() => {
    withdrawalServices
      .getWithdrawal(Number(withdrawalId))
      .then(setWithdrawal)
      .catch((error) => {
        handleApiError(error, 'An unexpected error occurred.')
        router.replace('/withdrawals')
      })
      .finally(() => {
        setIsLoading(false)
      })
  }, [withdrawalId, router])

  function handleViewTransferProof() {
    setTransferProofModal({
      type: 'view',
      isOpened: true,
    })
  }

  function handleProcessWithdrawal() {
    setConfirmationModal({ isOpen: true, loading: false })
  }

  async function handleConfirmProcess() {
    setConfirmationModal((prev) => ({ ...prev, loading: true }))

    try {
      const updatedWithdrawal = await withdrawalServices.processWithdrawal(
        Number(withdrawalId),
      )
      setWithdrawal(updatedWithdrawal)
      setConfirmationModal({ isOpen: false, loading: false })

      toast.success('Withdrawal processed successfully.')
    } catch (error) {
      handleApiError(error, 'Failed to process withdrawal.')
      setConfirmationModal((prev) => ({ ...prev, loading: false }))
    }
  }

  function handleCompleteWithdrawal() {
    setCompleteModal({ isOpen: true, loading: false })
  }

  async function handleConfirmComplete(
    formValues: CompleteWithdrawalFormValues,
  ) {
    setCompleteModal((prev) => ({ ...prev, loading: true }))

    try {
      const updatedWithdrawal = await withdrawalServices.completeWithdrawal(
        Number(withdrawalId),
        formValues,
      )

      setWithdrawal(updatedWithdrawal)
      setCompleteModal({ isOpen: false, loading: false })

      toast.success('Withdrawal completed successfully.')
    } catch (error) {
      handleApiError(error, 'Failed to complete withdrawal.')
      setCompleteModal((prev) => ({ ...prev, loading: false }))
    }
  }

  function handleRejectWithdrawal() {
    setRejectModal({ isOpen: true, loading: false })
  }

  async function handleConfirmReject(formValues: RejectWithdrawalFormValues) {
    setRejectModal((prev) => ({ ...prev, loading: true }))

    try {
      const updatedWithdrawal = await withdrawalServices.rejectWithdrawal(
        Number(withdrawalId),
        formValues,
      )

      setWithdrawal(updatedWithdrawal)
      setRejectModal({ isOpen: false, loading: false })

      toast.success('Withdrawal rejected successfully.')
    } catch (error) {
      handleApiError(error, 'Failed to reject withdrawal.')
      setRejectModal((prev) => ({ ...prev, loading: false }))
    }
  }

  useWithdrawalBroadcast({
    onWithdrawalCancelled: (data) => {
      if (Number(withdrawalId) === Number(data.id)) {
        // Refresh withdrawal details if the currently viewed withdrawal is cancelled
        withdrawalServices
          .getWithdrawal(Number(withdrawalId))
          .then(setWithdrawal)
          .catch((error) => {
            handleApiError(error, 'An unexpected error occurred.')
            router.replace('/withdrawals')
          })
      }
    },
  })

  // Authorize User
  useEffect(() => {
    if (user && user.role !== 'manager' && user.role !== 'accounting') {
      router.replace('/')
    }
  }, [user, router])

  if (isLoading) {
    return <FullPageLoader />
  }

  const statusColor: Record<string, string> = {
    pending: 'yellow',
    processing: 'blue',
    completed: 'green',
    rejected: 'red',
    cancelled: 'gray',
  }

  return (
    <article className="max-w-3xl mx-auto space-y-8 py-8">
      <Link
        href="/withdrawals"
        className="text-blue-500 hover:underline font-medium mb-8 flex items-center gap-2"
      >
        <IoIosArrowRoundBack className="inline w-6 h-6" />
        Back to Withdrawals
      </Link>

      {/* Withdrawal Summary */}
      <Card className="shadow-none">
        <h2 className="text-2xl font-semibold text-gray-900 mb-4">
          Withdrawal Summary
        </h2>

        <div className="grid grid-cols-1 space-y-5 sm:gap-2 sm:grid-cols-2">
          <div>
            <h3 className="text-sm font-medium text-gray-500">Code</h3>
            <p className="mt-1 text-gray-900 font-mono font-semibold">
              {withdrawal?.code}
            </p>
          </div>

          <div>
            <h3 className="text-sm font-medium text-gray-500">Status</h3>
            <Badge
              color={statusColor[withdrawal?.status || 'pending']}
              size="xs"
              className="w-fit mt-2"
            >
              {capitalizeWords(withdrawal?.status || '')}
            </Badge>
          </div>

          <div>
            <h3 className="text-sm font-medium text-gray-500">
              Requested Amount
            </h3>
            <p className="mt-1 text-gray-900">
              {formatIDR(withdrawal?.requested_amount || 0)}
            </p>
          </div>

          <div>
            <h3 className="text-sm font-medium text-gray-500">
              Withdrawal Fee
            </h3>
            <p className="mt-1 text-gray-900">
              {formatIDR(withdrawal?.withdrawal_fee || 0)}
            </p>
          </div>

          <div>
            <h3 className="text-sm font-medium text-gray-500 flex items-center gap-1">
              Net Amount
              <Tooltip content="This is the final amount after deducting the withdrawal fee. Transfer exactly this amount to the partner.">
                <FiHelpCircle className="h-3.5 w-3.5 text-gray-400 cursor-help" />
              </Tooltip>
            </h3>
            <p className="mt-1 text-gray-900 font-semibold">
              {formatIDR(withdrawal?.net_amount || 0)}
            </p>
          </div>
        </div>
      </Card>

      {/* Bank Details */}
      {withdrawal?.payout_method === PayoutMethod.BankTransfer && (
        <Card className="shadow-none">
          <h2 className="text-2xl font-semibold text-gray-900 mb-4">
            Bank Details
          </h2>

          <div className="grid grid-cols-1 space-y-5 sm:gap-2 sm:grid-cols-2">
            <div>
              <h3 className="text-sm font-medium text-gray-500">Bank Name</h3>
              <p className="mt-1 text-gray-900">
                {withdrawal?.bank_name || 'N/A'}
              </p>
            </div>

            <div>
              <h3 className="text-sm font-medium text-gray-500">
                Account Number
              </h3>
              <p className="mt-1 text-gray-900 font-mono font-semibold">
                {withdrawal?.account_number || 'N/A'}
              </p>
            </div>

            <div>
              <h3 className="text-sm font-medium text-gray-500">
                Account Name
              </h3>
              <p className="mt-1 text-gray-900">
                {withdrawal?.account_name || 'N/A'}
              </p>
            </div>
          </div>
        </Card>
      )}

      {/* Wise Details */}
      {withdrawal?.payout_method === PayoutMethod.Wise && (
        <Card className="shadow-none">
          <h2 className="text-2xl font-semibold text-gray-900 mb-4">
            Wise Details
          </h2>

          <div className="grid grid-cols-1 space-y-5 sm:gap-2 sm:grid-cols-2">
            <div>
              <h3 className="text-sm font-medium text-gray-500">
                Account Name
              </h3>
              <p className="mt-1 text-gray-900">
                {withdrawal?.wise_account_name || 'N/A'}
              </p>
            </div>

            <div>
              <h3 className="text-sm font-medium text-gray-500">Email</h3>
              <p className="mt-1 text-gray-900 break-words">
                {withdrawal?.wise_email || 'N/A'}
              </p>
            </div>
          </div>
        </Card>
      )}

      {/* Paypal Details */}
      {withdrawal?.payout_method === PayoutMethod.Paypal && (
        <Card className="shadow-none">
          <h2 className="text-2xl font-semibold text-gray-900 mb-4">
            Paypal Details
          </h2>

          <div className="grid grid-cols-1 space-y-5 sm:gap-2 sm:grid-cols-2">
            <div>
              <h3 className="text-sm font-medium text-gray-500">
                Account Name
              </h3>
              <p className="mt-1 text-gray-900">
                {withdrawal?.paypal_account_name || 'N/A'}
              </p>
            </div>

            <div>
              <h3 className="text-sm font-medium text-gray-500">Email</h3>
              <p className="mt-1 text-gray-900 break-words">
                {withdrawal?.paypal_email || 'N/A'}
              </p>
            </div>
          </div>
        </Card>
      )}

      {/* Partner Details - Business */}
      {(withdrawal?.partner?.partner_category === PartnerCategory.HotelVilla ||
        withdrawal?.partner?.partner_category ===
          PartnerCategory.Restaurant) && (
        <Card className="shadow-none">
          <h2 className="text-2xl font-semibold text-gray-900 mb-4">
            Business Details
          </h2>

          <div className="grid grid-cols-1 space-y-5 sm:gap-2 sm:grid-cols-2">
            <div>
              <h3 className="text-sm font-medium text-gray-500">
                Business Name
              </h3>
              <p className="mt-1 text-gray-900">
                {withdrawal?.partner?.business?.business_name || 'N/A'}
              </p>
            </div>

            <div>
              <h3 className="text-sm font-medium text-gray-500">
                Business Email
              </h3>
              <p className="mt-1 text-gray-900 break-words">
                {withdrawal?.partner?.business?.business_email || 'N/A'}
              </p>
            </div>

            <div>
              <h3 className="text-sm font-medium text-gray-500">PIC Name</h3>
              <p className="mt-1 text-gray-900">
                {withdrawal?.partner?.business?.pic_name || 'N/A'}
              </p>
            </div>

            <div>
              <h3 className="text-sm font-medium text-gray-500">PIC Email</h3>
              <p className="mt-1 text-gray-900 break-words">
                {withdrawal?.partner?.business?.pic_email || 'N/A'}
              </p>
            </div>

            <div>
              <h3 className="text-sm font-medium text-gray-500">PIC Phone</h3>
              <p className="mt-1 text-gray-900">
                {withdrawal?.partner?.business?.pic_phone_number || 'N/A'}
              </p>
            </div>
          </div>
        </Card>
      )}

      {/* Partner Details - Driver */}
      {withdrawal?.partner?.partner_category === PartnerCategory.Driver && (
        <Card className="shadow-none">
          <h2 className="text-2xl font-semibold text-gray-900 mb-4">
            Driver Details
          </h2>

          <div className="grid grid-cols-1 space-y-5 sm:gap-2 sm:grid-cols-2">
            <div>
              <h3 className="text-sm font-medium text-gray-500">Name</h3>
              <p className="mt-1 text-gray-900">
                {withdrawal?.partner?.driver?.name || 'N/A'}
              </p>
            </div>

            <div>
              <h3 className="text-sm font-medium text-gray-500">Email</h3>
              <p className="mt-1 text-gray-900 break-words">
                {withdrawal?.partner?.driver?.email || 'N/A'}
              </p>
            </div>

            <div>
              <h3 className="text-sm font-medium text-gray-500">
                Phone Number
              </h3>
              <p className="mt-1 text-gray-900">
                {withdrawal?.partner?.driver?.phone_number || 'N/A'}
              </p>
            </div>
          </div>
        </Card>
      )}

      {/* Notes */}
      {withdrawal?.notes && (
        <Card className="shadow-none">
          <h2 className="text-2xl font-semibold text-gray-900 mb-4">Notes</h2>
          <p className="text-gray-900 whitespace-pre-line">
            {withdrawal.notes}
          </p>
        </Card>
      )}

      {/* Rejection Reason */}
      {withdrawal?.rejection_reason && (
        <Card className="shadow-none">
          <h2 className="text-2xl font-semibold text-gray-900 mb-4">
            Rejection Reason
          </h2>
          <p className="text-gray-900 whitespace-pre-line">
            {withdrawal.rejection_reason}
          </p>
        </Card>
      )}

      {/* Cancellation Reason */}
      {withdrawal?.cancellation_reason && (
        <Card className="shadow-none">
          <h2 className="text-2xl font-semibold text-gray-900 mb-4">
            Cancellation Reason
          </h2>
          <p className="text-gray-900 whitespace-pre-line">
            {withdrawal.cancellation_reason}
          </p>
        </Card>
      )}

      {/* Action Buttons */}
      <div className="flex items-center justify-end flex-wrap gap-4">
        {withdrawal?.status === 'pending' && user?.role === 'accounting' && (
          <Button
            theme={buttonTheme.button}
            color="yellow"
            onClick={handleProcessWithdrawal}
          >
            <FiLoader className="h-4 w-4 mr-2" />
            Process
          </Button>
        )}

        {withdrawal?.status === 'processing' && user?.role === 'accounting' && (
          <React.Fragment>
            <Button
              theme={buttonTheme.button}
              color="red"
              onClick={handleRejectWithdrawal}
            >
              <FiX className="h-4 w-4 mr-2" />
              Reject
            </Button>
            <Button
              theme={buttonTheme.button}
              color="green"
              onClick={handleCompleteWithdrawal}
            >
              <FiCheck className="h-4 w-4 mr-2" />
              Complete
            </Button>
          </React.Fragment>
        )}

        {withdrawal?.status === 'completed' && (
          <Button
            theme={buttonTheme.button}
            color="blue"
            onClick={handleViewTransferProof}
          >
            <FiFile className="h-4 w-4 mr-2" />
            Transfer Proof
          </Button>
        )}
      </div>

      <ConfirmationModal
        isOpen={confirmationModal.isOpen}
        title="Process Withdrawal"
        message="Are you sure you want to process this withdrawal? This action cannot be undone."
        confirmText="Process"
        loading={confirmationModal.loading}
        onConfirm={handleConfirmProcess}
        onClose={() => setConfirmationModal({ isOpen: false, loading: false })}
      />

      <CompleteWithdrawalModal
        isOpen={completeModal.isOpen}
        loading={completeModal.loading}
        onConfirm={handleConfirmComplete}
        onClose={() => setCompleteModal({ isOpen: false, loading: false })}
      />

      <RejectWithdrawalModal
        isOpen={rejectModal.isOpen}
        loading={rejectModal.loading}
        onConfirm={handleConfirmReject}
        onClose={() => setRejectModal({ isOpen: false, loading: false })}
      />

      <TransferProofModal
        withdrawal={withdrawal}
        transferProofModal={transferProofModal}
        setTransferProofModal={setTransferProofModal}
      />
    </article>
  )
}
