﻿"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 { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
  Loader2,
  Send,
  Building2,
  CreditCard,
  User,
  Wallet,
} from "lucide-react";
import {
  sendMoneySchema,
  type SendMoneyInput,
} from "@/lib/validations/withdrawal";
import type { WithdrawRequest } from "@/features/payment/services/withdrawals.service";

interface SendMoneyDialogProps {
  withdrawal: WithdrawRequest | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onConfirm: (amount: number, referenceNumber: string) => void;
}

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

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

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<SendMoneyInput>({
    resolver: zodResolver(sendMoneySchema),
    defaultValues: {
      amount: withdrawal?.withdrawAmount || 0,
      referenceNumber: "",
    },
  });

  const onSubmit = async (data: SendMoneyInput) => {
    setIsSubmitting(true);
    // Simulate network delay
    await new Promise((resolve) => setTimeout(resolve, 500));
    onConfirm(data.amount, data.referenceNumber);
    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-[500px] max-h-[90vh] flex flex-col">
        <DialogHeader className="flex-shrink-0">
          <DialogTitle className="flex items-center gap-2">
            <Send className="h-5 w-5 text-primary" aria-hidden="true" />
            Send Money
          </DialogTitle>
          <DialogDescription>
            Process withdrawal request for {withdrawal.name}
          </DialogDescription>
        </DialogHeader>

        <form
          onSubmit={handleSubmit(onSubmit)}
          className="flex flex-col flex-1 overflow-hidden"
        >
          <ScrollArea className="flex-1 overflow-auto pr-4">
            <div className="space-y-6 pb-2">
              {/* User Information */}
              <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
                <h4 className="font-medium text-sm flex items-center gap-2">
                  <User className="h-4 w-4" aria-hidden="true" />
                  Requester Information
                </h4>
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div>
                    <span className="text-muted-foreground">Name:</span>
                    <p className="font-medium">{withdrawal.name}</p>
                  </div>
                  <div>
                    <span className="text-muted-foreground">Email:</span>
                    <p className="font-medium break-all">{withdrawal.email}</p>
                  </div>
                  <div>
                    <span className="text-muted-foreground">Phone:</span>
                    <p className="font-medium">{withdrawal.phone}</p>
                  </div>
                  <div>
                    <span className="text-muted-foreground flex items-center gap-1">
                      <Wallet className="h-3 w-3" aria-hidden="true" />
                      Wallet Balance:
                    </span>
                    <p className="font-medium text-green-600">
                      {formatCurrency(withdrawal.walletBalance)}
                    </p>
                  </div>
                </div>
              </div>

              <Separator />

              {/* Bank Details */}
              <div className="rounded-lg border bg-muted/30 p-4 space-y-3">
                <h4 className="font-medium text-sm flex items-center gap-2">
                  <Building2 className="h-4 w-4" aria-hidden="true" />
                  Bank Details
                </h4>
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div>
                    <span className="text-muted-foreground">
                      Account Holder:
                    </span>
                    <p className="font-medium">
                      {withdrawal.bankDetails.accountHolder}
                    </p>
                  </div>
                  <div>
                    <span className="text-muted-foreground">Bank Name:</span>
                    <p className="font-medium">
                      {withdrawal.bankDetails.bankName}
                    </p>
                  </div>
                  <div>
                    <span className="text-muted-foreground">
                      Account Number:
                    </span>
                    <p className="font-medium font-mono">
                      {withdrawal.bankDetails.accountNumber}
                    </p>
                  </div>
                  <div>
                    <span className="text-muted-foreground">IFSC Code:</span>
                    <p className="font-medium font-mono">
                      {withdrawal.bankDetails.ifscCode}
                    </p>
                  </div>
                </div>
              </div>

              <Separator />

              {/* Transfer Details */}
              <div className="space-y-4">
                <h4 className="font-medium text-sm flex items-center gap-2">
                  <CreditCard className="h-4 w-4" aria-hidden="true" />
                  Transfer Details
                </h4>

                <div className="space-y-2">
                  <Label htmlFor="amount">Amount to Send *</Label>
                  <Input
                    id="amount"
                    type="number"
                    defaultValue={withdrawal.withdrawAmount}
                    {...register("amount", { valueAsNumber: true })}
                    placeholder="Enter amount"
                    aria-describedby={
                      errors.amount ? "amount-error" : undefined
                    }
                  />
                  {errors.amount && (
                    <p id="amount-error" className="text-sm text-destructive">
                      {errors.amount.message}
                    </p>
                  )}
                  <p className="text-xs text-muted-foreground">
                    Requested amount:{" "}
                    {formatCurrency(withdrawal.withdrawAmount)}
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="referenceNumber">Reference Number *</Label>
                  <Input
                    id="referenceNumber"
                    {...register("referenceNumber")}
                    placeholder="Enter transaction reference number"
                    aria-describedby={
                      errors.referenceNumber ? "ref-error" : undefined
                    }
                  />
                  {errors.referenceNumber && (
                    <p id="ref-error" className="text-sm text-destructive">
                      {errors.referenceNumber.message}
                    </p>
                  )}
                  <p className="text-xs text-muted-foreground">
                    Enter the bank transaction reference or UTR number
                  </p>
                </div>
              </div>
            </div>
          </ScrollArea>

          <DialogFooter className="flex-shrink-0 pt-4 border-t mt-4">
            <Button
              type="button"
              variant="outline"
              onClick={() => handleClose(false)}
              disabled={isSubmitting}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting ? (
                <>
                  <Loader2
                    className="mr-2 h-4 w-4 animate-spin"
                    aria-hidden="true"
                  />
                  Processing...
                </>
              ) : (
                <>
                  <Send className="mr-2 h-4 w-4" aria-hidden="true" />
                  Send Money
                </>
              )}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
