"use client"

import { useState } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Loader2, XCircle, AlertTriangle } from "lucide-react"
import { cancelWithdrawalSchema, type CancelWithdrawalInput } from "@/lib/validations/withdrawal"
import type { WithdrawRequest } from "@/lib/data/withdrawals"

interface CancelWithdrawDialogProps {
  withdrawal: WithdrawRequest | null
  open: boolean
  onOpenChange: (open: boolean) => void
  onConfirm: (reason: string) => void
}

function formatCurrency(amount: number): string {
  return new Intl.NumberFormat("en-IN", {
    style: "currency",
    currency: "INR",
    maximumFractionDigits: 0,
  }).format(amount)
}

export function CancelWithdrawDialog({ withdrawal, open, onOpenChange, onConfirm }: CancelWithdrawDialogProps) {
  const [isSubmitting, setIsSubmitting] = useState(false)

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<CancelWithdrawalInput>({
    resolver: zodResolver(cancelWithdrawalSchema),
  })

  const onSubmit = async (data: CancelWithdrawalInput) => {
    setIsSubmitting(true)
    // Simulate network delay
    await new Promise((resolve) => setTimeout(resolve, 500))
    onConfirm(data.reason)
    reset()
    setIsSubmitting(false)
  }

  const handleClose = (open: boolean) => {
    if (!open) reset()
    onOpenChange(open)
  }

  if (!withdrawal) return null

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[450px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2 text-destructive">
            <XCircle className="h-5 w-5" aria-hidden="true" />
            Cancel Withdrawal
          </DialogTitle>
          <DialogDescription>Are you sure you want to cancel this withdrawal request?</DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          {/* Warning */}
          <div className="flex items-start gap-3 rounded-lg border border-amber-200 bg-amber-50 p-4 dark:border-amber-900 dark:bg-amber-950/30">
            <AlertTriangle className="h-5 w-5 text-amber-600 shrink-0 mt-0.5" aria-hidden="true" />
            <div className="text-sm">
              <p className="font-medium text-amber-800 dark:text-amber-200">This action cannot be undone</p>
              <p className="text-amber-700 dark:text-amber-300 mt-1">
                Cancelling will reject the withdrawal of <strong>{formatCurrency(withdrawal.withdrawAmount)}</strong>{" "}
                requested by <strong>{withdrawal.name}</strong>.
              </p>
            </div>
          </div>

          {/* Reason */}
          <div className="space-y-2">
            <Label htmlFor="reason">Reason for Cancellation *</Label>
            <Textarea
              id="reason"
              {...register("reason")}
              placeholder="Enter the reason for cancelling this withdrawal request..."
              rows={4}
              aria-describedby={errors.reason ? "reason-error" : undefined}
            />
            {errors.reason && (
              <p id="reason-error" className="text-sm text-destructive">
                {errors.reason.message}
              </p>
            )}
            <p className="text-xs text-muted-foreground">This reason will be visible to the requester.</p>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => handleClose(false)} disabled={isSubmitting}>
              Go Back
            </Button>
            <Button type="submit" variant="destructive" disabled={isSubmitting}>
              {isSubmitting ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />
                  Cancelling...
                </>
              ) : (
                <>
                  <XCircle className="mr-2 h-4 w-4" aria-hidden="true" />
                  Cancel Withdrawal
                </>
              )}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
