'use client'

import { 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 { FiFile, FiHelpCircle, FiX } from 'react-icons/fi'

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 { formatIDR } from '@/lib/utils/currency'
import buttonTheme from '@/lib/themes/button'
import { Withdrawal } from '@/lib/types/withdrawal'
import { useAuth } from '@/lib/context/AuthContext'
import { useBroadcast } from '@/lib/hooks/useBroadcast'
import TransferProofModal from '../_partials/TransferProofModal'
import WithdrawalCancelledModal from '../_partials/WithdrawalCancelledModal'

interface MainContentProps {
  withdrawalId: string
}

export default function MainContent({ withdrawalId }: MainContentProps) {
  const router = useRouter()
  const [isLoading, setIsLoading] = useState(true)
  const [withdrawal, setWithdrawal] = useState<Withdrawal | null>(null)
  const [transferProofModal, setTransferProofModal] = useState<ModalState>({
    type: 'view',
    isOpened: false,
  })
  const { user } = useAuth()
  const [withdrawalCancelledModal, setWithdrawalCancelledModal] =
    useState<ModalState>({
      type: 'edit',
      isOpened: 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,
    })
  }

  useBroadcast({
    partnerId: user?.id || 0,
    onWithdrawalRejected: (data) => {
      if (Number(withdrawalId) === Number(data.id)) {
        withdrawalServices
          .getWithdrawal(Number(withdrawalId))
          .then(setWithdrawal)
          .catch((error) => {
            console.error('Error fetching withdrawal details:', error)
            router.replace('/withdrawals')
          })
      }
    },
    onWithdrawalCompleted: (data) => {
      if (Number(withdrawalId) === Number(data.id)) {
        withdrawalServices
          .getWithdrawal(Number(withdrawalId))
          .then(setWithdrawal)
          .catch((error) => {
            console.error('Error fetching withdrawal details:', error)
            router.replace('/withdrawals')
          })
      }
    },
    onWithdrawalProcessed: (data) => {
      if (Number(withdrawalId) === Number(data.id)) {
        withdrawalServices
          .getWithdrawal(Number(withdrawalId))
          .then(setWithdrawal)
          .catch((error) => {
            console.error('Error fetching withdrawal details:', error)
            router.replace('/withdrawals')
          })
      }
    },
  })

  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 agent.">
                <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 === 'bank_transfer' && (
        <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 === '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">
                {withdrawal?.wise_email || 'N/A'}
              </p>
            </div>
          </div>
        </Card>
      )}

      {/* Paypal Details */}
      {withdrawal?.payout_method === '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">
                {withdrawal?.paypal_email || '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' ||
          withdrawal?.status === 'processing') && (
          <Button
            theme={buttonTheme.button}
            color="red"
            onClick={() => {
              setWithdrawalCancelledModal({ type: 'edit', isOpened: true })
            }}
          >
            <FiX className="h-4 w-4 mr-2" />
            Cancel Withdrawal
          </Button>
        )}

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

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

      <WithdrawalCancelledModal
        withdrawal={withdrawal}
        withdrawalCancelledModal={withdrawalCancelledModal}
        setWithdrawalCancelledModal={setWithdrawalCancelledModal}
        onSuccess={setWithdrawal}
      />
    </article>
  )
}
