'use client';

import { useEffect, useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { AlertTriangle, ExternalLink } from 'lucide-react';
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetDescription,
} from '@/components/ui/sheet';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import { Spinner } from '@/components/ui/spinners';
import {
  approveWithdrawal,
  markWithdrawalPaid,
  rejectWithdrawal,
} from '@/network/apis/dashboard/marketplace/marketplace.apis';
import { Withdrawal } from '@/network/apis/dashboard/marketplace/type';
import { StatusPill } from './StatusPill';
import { CopyButton } from './CopyButton';

const HIGH_VALUE_THRESHOLD = 10000;

const safeFormat = (value: string | null | undefined) => {
  if (!value) return '—';
  try {
    return format(new Date(value), 'PP p');
  } catch {
    return value;
  }
};

const formatMoney = (amount: number, currency: string) =>
  new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: currency || 'SAR',
    maximumFractionDigits: 2,
  }).format(amount);

export function WithdrawalDetailSheet({
  withdrawal,
  open,
  onClose,
}: {
  withdrawal: Withdrawal | null;
  open: boolean;
  onClose: () => void;
}) {
  const queryClient = useQueryClient();
  const [adminNotes, setAdminNotes] = useState('');
  const [confirmKind, setConfirmKind] = useState<
    'approve' | 'reject' | 'pay' | null
  >(null);
  const [rejectionReason, setRejectionReason] = useState('');
  const [paymentReference, setPaymentReference] = useState('');
  const [paymentMethod, setPaymentMethod] = useState('bank_transfer');
  const [confirmText, setConfirmText] = useState('');

  useEffect(() => {
    setAdminNotes(withdrawal?.admin_notes ?? '');
    setRejectionReason('');
    setPaymentReference('');
    setPaymentMethod('bank_transfer');
    setConfirmText('');
    setConfirmKind(null);
  }, [withdrawal?.id]);

  const invalidate = () => {
    queryClient.invalidateQueries({ queryKey: ['withdrawals'] });
    queryClient.invalidateQueries({ queryKey: ['withdrawals-kpi'] });
  };

  const handleError = (error: unknown, fallback: string) => {
    const msg =
      (error as { response?: { data?: { message?: string } } })?.response?.data
        ?.message || fallback;
    toast.error(msg);
  };

  const approveMutation = useMutation({
    mutationFn: (id: number) => approveWithdrawal(id),
    onSuccess: () => {
      toast.success('Withdrawal approved');
      invalidate();
      setConfirmKind(null);
      onClose();
    },
    onError: (e) => handleError(e, 'Failed to approve'),
  });

  const rejectMutation = useMutation({
    mutationFn: (id: number) =>
      rejectWithdrawal(id, {
        rejection_reason: rejectionReason.trim(),
        admin_notes: adminNotes.trim() || undefined,
      }),
    onSuccess: () => {
      toast.success('Withdrawal rejected');
      invalidate();
      setConfirmKind(null);
      onClose();
    },
    onError: (e) => handleError(e, 'Failed to reject'),
  });

  const markPaidMutation = useMutation({
    mutationFn: (id: number) =>
      markWithdrawalPaid(id, {
        payment_reference: paymentReference.trim(),
        payment_method: paymentMethod.trim() || undefined,
        admin_notes: adminNotes.trim() || undefined,
      }),
    onSuccess: () => {
      toast.success('Marked as paid');
      invalidate();
      setConfirmKind(null);
      onClose();
    },
    onError: (e) => handleError(e, 'Failed to mark paid'),
  });

  if (!withdrawal) return null;

  const status = withdrawal.status;
  const isHighValue = withdrawal.amount >= HIGH_VALUE_THRESHOLD;
  const requiredConfirmText = `WITHDRAW-${withdrawal.id}`;
  const confirmTextOk = !isHighValue || confirmText === requiredConfirmText;

  const canApprove = status === 'requested';
  const canReject = status === 'requested' || status === 'approved';
  const canMarkPaid = status === 'approved';

  const submitting =
    approveMutation.isPending ||
    rejectMutation.isPending ||
    markPaidMutation.isPending;

  return (
    <>
      <Sheet open={open} onOpenChange={(o) => !o && onClose()}>
        <SheetContent
          side="right"
          className="w-full sm:max-w-xl overflow-y-auto"
        >
          <SheetHeader>
            <SheetTitle className="flex items-center gap-3">
              Withdrawal #{withdrawal.id}
              <StatusPill status={withdrawal.status} />
            </SheetTitle>
            <SheetDescription>
              Submitted {safeFormat(withdrawal.requested_at)}
            </SheetDescription>
          </SheetHeader>

          <div className="space-y-6 px-4 pb-6">
            {/* Amount */}
            <div className="rounded-lg border p-4">
              <div className="text-xs uppercase text-muted-foreground">
                Amount
              </div>
              <div className="text-2xl font-semibold">
                {formatMoney(withdrawal.amount, withdrawal.currency)}
              </div>
            </div>

            {/* Creator */}
            <div className="space-y-2">
              <h3 className="text-sm font-semibold">Creator</h3>
              <div className="rounded-lg border p-3 flex items-start justify-between gap-3">
                <div>
                  <div className="font-medium">
                    {withdrawal.creator?.display_name ||
                      withdrawal.creator?.username}
                  </div>
                  <div className="text-sm text-muted-foreground">
                    @{withdrawal.creator?.username} · ID #
                    {withdrawal.creator?.id}
                  </div>
                </div>
                {withdrawal.creator?.user_id ? (
                  <Button
                    variant="outline"
                    size="sm"
                    asChild
                    title="Open creator profile"
                  >
                    <a
                      href={`/client-management/${withdrawal.creator.user_id}`}
                      target="_blank"
                      rel="noopener"
                    >
                      <ExternalLink className="size-4" />
                    </a>
                  </Button>
                ) : null}
              </div>
            </div>

            {/* Bank snapshot */}
            <div className="space-y-2">
              <h3 className="text-sm font-semibold">
                Bank details at submission
              </h3>
              <div className="rounded-lg border p-3 space-y-2 text-sm">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="text-xs text-muted-foreground">
                      Account holder
                    </div>
                    <div className="font-medium">
                      {withdrawal.bank_snapshot?.account_holder || '—'}
                    </div>
                  </div>
                  {withdrawal.bank_snapshot?.account_holder ? (
                    <CopyButton
                      value={withdrawal.bank_snapshot.account_holder}
                      label="Account holder"
                    />
                  ) : null}
                </div>
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="text-xs text-muted-foreground">
                      Bank name
                    </div>
                    <div className="font-medium">
                      {withdrawal.bank_snapshot?.bank_name || '—'}
                    </div>
                  </div>
                </div>
                <div className="flex items-start justify-between gap-3">
                  <div className="min-w-0">
                    <div className="text-xs text-muted-foreground">IBAN</div>
                    <div className="font-mono text-sm break-all">
                      {withdrawal.bank_snapshot?.iban || '—'}
                    </div>
                  </div>
                  {withdrawal.bank_snapshot?.iban ? (
                    <CopyButton
                      value={withdrawal.bank_snapshot.iban}
                      label="IBAN"
                    />
                  ) : null}
                </div>
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="text-xs text-muted-foreground">
                      Account number
                    </div>
                    <div className="font-mono text-sm">
                      {withdrawal.bank_snapshot?.account_number || '—'}
                    </div>
                  </div>
                  {withdrawal.bank_snapshot?.account_number ? (
                    <CopyButton
                      value={withdrawal.bank_snapshot.account_number}
                      label="Account number"
                    />
                  ) : null}
                </div>
              </div>
            </div>

            {/* Creator notes */}
            {withdrawal.creator_notes ? (
              <div className="space-y-2">
                <h3 className="text-sm font-semibold">Creator note</h3>
                <div className="rounded-lg border p-3 text-sm whitespace-pre-wrap">
                  {withdrawal.creator_notes}
                </div>
              </div>
            ) : null}

            {/* Status timeline */}
            <div className="space-y-2">
              <h3 className="text-sm font-semibold">Timeline</h3>
              <div className="rounded-lg border p-3 text-sm space-y-1">
                <div>
                  <span className="text-muted-foreground">Requested:</span>{' '}
                  {safeFormat(withdrawal.requested_at)}
                </div>
                <div>
                  <span className="text-muted-foreground">Approved:</span>{' '}
                  {safeFormat(withdrawal.approved_at)}
                </div>
                <div>
                  <span className="text-muted-foreground">Paid:</span>{' '}
                  {safeFormat(withdrawal.paid_at)}
                </div>
                <div>
                  <span className="text-muted-foreground">Rejected:</span>{' '}
                  {safeFormat(withdrawal.rejected_at)}
                </div>
                <div>
                  <span className="text-muted-foreground">Cancelled:</span>{' '}
                  {safeFormat(withdrawal.cancelled_at)}
                </div>
              </div>
              {withdrawal.reviewer ? (
                <div className="text-xs text-muted-foreground">
                  Reviewed by: {withdrawal.reviewer.name}
                </div>
              ) : null}
            </div>

            {/* Existing rejection reason / payment reference */}
            {withdrawal.rejection_reason ? (
              <div className="space-y-2">
                <h3 className="text-sm font-semibold text-red-600">
                  Rejection reason
                </h3>
                <div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm whitespace-pre-wrap">
                  {withdrawal.rejection_reason}
                </div>
              </div>
            ) : null}
            {withdrawal.payment_reference ? (
              <div className="space-y-2">
                <h3 className="text-sm font-semibold">Payment reference</h3>
                <div className="rounded-lg border p-3 text-sm font-mono">
                  {withdrawal.payment_reference}
                  {withdrawal.payment_method
                    ? ` · ${withdrawal.payment_method}`
                    : ''}
                </div>
              </div>
            ) : null}

            {/* Admin notes (editable) */}
            <div className="space-y-2">
              <Label>Admin notes</Label>
              <Textarea
                value={adminNotes}
                onChange={(e) => setAdminNotes(e.target.value)}
                placeholder="Internal notes for the team"
                rows={3}
              />
              <p className="text-xs text-muted-foreground">
                Notes are persisted when you confirm Reject or Mark Paid below.
              </p>
            </div>

            {/* Action buttons */}
            <div className="flex flex-wrap gap-2 pt-2 border-t">
              {canApprove ? (
                <Button
                  onClick={() => setConfirmKind('approve')}
                  disabled={submitting}
                >
                  Approve
                </Button>
              ) : null}
              {canMarkPaid ? (
                <Button
                  onClick={() => setConfirmKind('pay')}
                  disabled={submitting}
                  className="bg-green-600 hover:bg-green-700 text-white"
                >
                  Mark as Paid
                </Button>
              ) : null}
              {canReject ? (
                <Button
                  variant="outline"
                  onClick={() => setConfirmKind('reject')}
                  disabled={submitting}
                  className="text-red-600 border-red-200 hover:bg-red-50"
                >
                  Reject
                </Button>
              ) : null}
            </div>
          </div>
        </SheetContent>
      </Sheet>

      {/* Approve confirm */}
      <Dialog
        open={confirmKind === 'approve'}
        onOpenChange={(o) => !o && setConfirmKind(null)}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Approve withdrawal #{withdrawal.id}?</DialogTitle>
            <DialogDescription>
              You will lock {formatMoney(withdrawal.amount, withdrawal.currency)} for{' '}
              {withdrawal.creator?.username}. The creator can no longer cancel
              after this.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setConfirmKind(null)}>
              Cancel
            </Button>
            <Button
              onClick={() => approveMutation.mutate(withdrawal.id)}
              disabled={approveMutation.isPending}
            >
              {approveMutation.isPending ? (
                <Spinner className="size-4 animate-spin mr-2" />
              ) : null}
              Confirm approve
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Reject confirm */}
      <Dialog
        open={confirmKind === 'reject'}
        onOpenChange={(o) => !o && setConfirmKind(null)}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Reject withdrawal #{withdrawal.id}?</DialogTitle>
            <DialogDescription>
              {formatMoney(withdrawal.amount, withdrawal.currency)} will be
              released back to the creator's available balance.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            <div>
              <Label>
                Rejection reason <span className="text-red-500">*</span>
              </Label>
              <Textarea
                value={rejectionReason}
                onChange={(e) => setRejectionReason(e.target.value)}
                placeholder="Required, 3-2000 characters. Visible to the creator."
                rows={4}
              />
              <p className="text-xs text-muted-foreground mt-1">
                {rejectionReason.length} / 2000
              </p>
            </div>
            {isHighValue ? (
              <div className="rounded-lg border border-amber-300 bg-amber-50 p-3 text-sm space-y-2">
                <div className="flex items-center gap-2 font-semibold text-amber-800">
                  <AlertTriangle className="size-4" /> High-value action
                </div>
                <Label>
                  Type{' '}
                  <span className="font-mono">{requiredConfirmText}</span> to
                  confirm
                </Label>
                <Input
                  value={confirmText}
                  onChange={(e) => setConfirmText(e.target.value)}
                  placeholder={requiredConfirmText}
                />
              </div>
            ) : null}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setConfirmKind(null)}>
              Cancel
            </Button>
            <Button
              variant="outline"
              className="text-red-600 border-red-300 hover:bg-red-50"
              onClick={() => rejectMutation.mutate(withdrawal.id)}
              disabled={
                rejectMutation.isPending ||
                rejectionReason.trim().length < 3 ||
                rejectionReason.length > 2000 ||
                !confirmTextOk
              }
            >
              {rejectMutation.isPending ? (
                <Spinner className="size-4 animate-spin mr-2" />
              ) : null}
              Confirm reject
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Mark paid confirm */}
      <Dialog
        open={confirmKind === 'pay'}
        onOpenChange={(o) => !o && setConfirmKind(null)}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Mark withdrawal #{withdrawal.id} as paid?</DialogTitle>
            <DialogDescription>
              Confirm you have wired{' '}
              {formatMoney(withdrawal.amount, withdrawal.currency)} to{' '}
              {withdrawal.bank_snapshot?.iban}. This is a terminal action.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            <div>
              <Label>
                Payment reference <span className="text-red-500">*</span>
              </Label>
              <Input
                value={paymentReference}
                onChange={(e) => setPaymentReference(e.target.value)}
                placeholder="e.g. MOY_REF_998877"
                maxLength={191}
              />
            </div>
            <div>
              <Label>Payment method</Label>
              <Input
                value={paymentMethod}
                onChange={(e) => setPaymentMethod(e.target.value)}
                placeholder="bank_transfer"
                maxLength={32}
              />
            </div>
            {isHighValue ? (
              <div className="rounded-lg border border-amber-300 bg-amber-50 p-3 text-sm space-y-2">
                <div className="flex items-center gap-2 font-semibold text-amber-800">
                  <AlertTriangle className="size-4" /> High-value action
                </div>
                <Label>
                  Type{' '}
                  <span className="font-mono">{requiredConfirmText}</span> to
                  confirm
                </Label>
                <Input
                  value={confirmText}
                  onChange={(e) => setConfirmText(e.target.value)}
                  placeholder={requiredConfirmText}
                />
              </div>
            ) : null}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setConfirmKind(null)}>
              Cancel
            </Button>
            <Button
              className="bg-green-600 hover:bg-green-700 text-white"
              onClick={() => markPaidMutation.mutate(withdrawal.id)}
              disabled={
                markPaidMutation.isPending ||
                paymentReference.trim().length === 0 ||
                !confirmTextOk
              }
            >
              {markPaidMutation.isPending ? (
                <Spinner className="size-4 animate-spin mr-2" />
              ) : null}
              Confirm paid
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
