import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/hooks/use-auth";
import { toast } from "sonner";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";

type Props = {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  orderId: string;
  orderNo: string;
  customerId: string | null;
  maxAmount: number;
  isBn: boolean;
};

export function RefundDialog({
  open,
  onOpenChange,
  orderId,
  orderNo,
  customerId,
  maxAmount,
  isBn,
}: Props) {
  const { user } = useAuth();
  const qc = useQueryClient();
  const [amount, setAmount] = useState<string>(maxAmount > 0 ? String(maxAmount) : "");
  const [method, setMethod] = useState("cash");
  const [note, setNote] = useState("");

  const mutation = useMutation({
    mutationFn: async () => {
      if (!customerId) throw new Error(isBn ? "গ্রাহক নেই" : "Customer required");
      const amt = Number(amount);
      if (!amt || amt <= 0) throw new Error(isBn ? "সঠিক পরিমাণ দিন" : "Enter valid amount");
      const finalNote = `Order: ${orderNo}${note ? " — " + note : ""}`;
      const { error } = await supabase.from("refunds").insert({
        customer_id: customerId,
        amount: amt,
        payment_method: method,
        note: finalNote,
        status: "completed",
        processed_by: user?.id ?? null,
      } as any);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(isBn ? "রিফান্ড সম্পন্ন হয়েছে" : "Refund recorded");
      qc.invalidateQueries({ queryKey: ["order-refunds", orderId] });
      qc.invalidateQueries({ queryKey: ["sales-order", orderId] });
      onOpenChange(false);
      setAmount("");
      setNote("");
    },
    onError: (e: any) => toast.error(e.message),
  });

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{isBn ? "রিফান্ড ইস্যু করুন" : "Issue Refund"}</DialogTitle>
        </DialogHeader>
        <div className="space-y-3">
          <div className="rounded-md bg-muted/40 p-3 text-xs">
            <div>{isBn ? "অর্ডার:" : "Order:"} <span className="font-mono">{orderNo}</span></div>
            <div>{isBn ? "সর্বোচ্চ:" : "Max:"} ৳{maxAmount.toLocaleString()}</div>
          </div>
          <div>
            <Label>{isBn ? "পরিমাণ *" : "Amount *"}</Label>
            <Input
              type="number"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              max={maxAmount || undefined}
            />
          </div>
          <div>
            <Label>{isBn ? "মাধ্যম" : "Method"}</Label>
            <Select value={method} onValueChange={setMethod}>
              <SelectTrigger><SelectValue /></SelectTrigger>
              <SelectContent>
                <SelectItem value="cash">Cash</SelectItem>
                <SelectItem value="bkash">bKash</SelectItem>
                <SelectItem value="nagad">Nagad</SelectItem>
                <SelectItem value="rocket">Rocket</SelectItem>
                <SelectItem value="bank">Bank</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div>
            <Label>{isBn ? "নোট" : "Note"}</Label>
            <Textarea rows={2} value={note} onChange={(e) => setNote(e.target.value)} />
          </div>
        </div>
        <DialogFooter>
          <Button variant="ghost" onClick={() => onOpenChange(false)}>
            {isBn ? "বাতিল" : "Cancel"}
          </Button>
          <Button onClick={() => mutation.mutate()} disabled={mutation.isPending}>
            {mutation.isPending ? "..." : isBn ? "রিফান্ড নিশ্চিত" : "Confirm Refund"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
