import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import { useLanguage } from "@/hooks/use-language";
import { nextStatuses, statusLabel, STATUS_COLORS, type SaleStatus } from "./sale-status";
import { useSaleStatusRules } from "@/hooks/use-sale-status-rules";
import { ChevronDown } from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";

export function SaleStatusDropdown({
  orderId,
  current,
  onChanged,
}: {
  orderId: string;
  current: string;
  onChanged?: () => void;
}) {
  const { lang } = useLanguage();
  const isBn = lang === "bn";
  const qc = useQueryClient();
  const [cancelOpen, setCancelOpen] = useState(false);
  const [cancelReason, setCancelReason] = useState("");

  const mutation = useMutation({
    mutationFn: async (payload: { status: SaleStatus; reason?: string }) => {
      const update: Record<string, unknown> = { status: payload.status };
      if (payload.status === "cancelled") update.cancelled_reason = payload.reason || "";
      const { error } = await supabase.from("sales_orders" as any).update(update).eq("id", orderId);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(isBn ? "স্ট্যাটাস আপডেট হয়েছে" : "Status updated");
      qc.invalidateQueries({ queryKey: ["sales-orders"] });
      qc.invalidateQueries({ queryKey: ["sales-order", orderId] });
      onChanged?.();
    },
    onError: (e: any) => toast.error(e.message),
  });

  const { getNext } = useSaleStatusRules();
  const options = getNext(current);
  const currentCls = STATUS_COLORS[current as SaleStatus] || "bg-muted text-muted-foreground border-border";

  const handlePick = (s: SaleStatus) => {
    if (s === "cancelled") {
      setCancelReason("");
      setCancelOpen(true);
      return;
    }
    mutation.mutate({ status: s });
  };

  return (
    <>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <button
            disabled={options.length === 0 || mutation.isPending}
            className={`inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-semibold ${currentCls} ${options.length === 0 ? "opacity-70 cursor-not-allowed" : "hover:opacity-90"}`}
          >
            {statusLabel(current, isBn)}
            {options.length > 0 && <ChevronDown className="h-3 w-3" />}
          </button>
        </DropdownMenuTrigger>
        {options.length > 0 && (
          <DropdownMenuContent align="end" className="w-44">
            {options.map((s) => (
              <DropdownMenuItem key={s} onClick={() => handlePick(s)}>
                {statusLabel(s, isBn)}
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        )}
      </DropdownMenu>

      <Dialog open={cancelOpen} onOpenChange={setCancelOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{isBn ? "অর্ডার বাতিল করুন" : "Cancel Order"}</DialogTitle>
          </DialogHeader>
          <div className="space-y-2">
            <label className="text-sm text-muted-foreground">
              {isBn ? "কারণ (আবশ্যক)" : "Reason (required)"}
            </label>
            <textarea
              value={cancelReason}
              onChange={(e) => setCancelReason(e.target.value)}
              rows={3}
              className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
              placeholder={isBn ? "বাতিলের কারণ লিখুন" : "Why are you cancelling?"}
            />
          </div>
          <DialogFooter>
            <button
              onClick={() => setCancelOpen(false)}
              className="rounded-md border border-border px-3 py-2 text-sm"
            >
              {isBn ? "বন্ধ" : "Close"}
            </button>
            <button
              disabled={!cancelReason.trim() || mutation.isPending}
              onClick={() => {
                mutation.mutate(
                  { status: "cancelled", reason: cancelReason.trim() },
                  { onSuccess: () => setCancelOpen(false) }
                );
              }}
              className="rounded-md bg-destructive px-3 py-2 text-sm text-destructive-foreground disabled:opacity-50"
            >
              {isBn ? "নিশ্চিত বাতিল" : "Confirm Cancel"}
            </button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
