"use client";

import { createContext, useCallback, useContext, useRef, useState } from "react";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { useTranslation } from "@/hooks/useTranslation";

type ConfirmVariant = "danger" | "primary";

export type ConfirmOptions = {
  title: string;
  description?: string;
  confirmText?: string;
  cancelText?: string;
  variant?: ConfirmVariant;
};

type ConfirmContextValue = (options: ConfirmOptions) => Promise<boolean>;

const ConfirmContext = createContext<ConfirmContextValue | null>(null);

export function ConfirmProvider({ children }: { children: React.ReactNode }) {
  const { t } = useTranslation();
  const resolverRef = useRef<((value: boolean) => void) | null>(null);
  const [state, setState] = useState<{
    open: boolean;
    options: ConfirmOptions | null;
  }>({
    open: false,
    options: null,
  });

  const confirm = useCallback((options: ConfirmOptions) => {
    return new Promise<boolean>((resolve) => {
      if (resolverRef.current) {
        resolverRef.current(false);
      }
      resolverRef.current = resolve;
      setState({ open: true, options });
    });
  }, []);

  const resolveAndClose = (result: boolean) => {
    setState((prev) => ({ ...prev, open: false }));
    if (resolverRef.current) {
      resolverRef.current(result);
      resolverRef.current = null;
    }
  };

  const options = state.options;
  const variant = options?.variant ?? "primary";
  const confirmText = options?.confirmText ?? t.common.confirm;
  const cancelText = options?.cancelText ?? t.common.cancel;

  return (
    <ConfirmContext.Provider value={confirm}>
      {children}
      <Dialog
        open={state.open}
        onOpenChange={(open) => {
          if (!open) {
            resolveAndClose(false);
          }
        }}
      >
        <DialogContent className="border-[#e5e6eb]">
          <DialogHeader className="space-y-2">
            <DialogTitle className="flex items-center gap-2">
              <span
                className={`h-2 w-2 rounded-full ${
                  variant === "danger" ? "bg-[#f53f3f]" : "bg-[#3370ff]"
                }`}
              />
              {options?.title}
            </DialogTitle>
            {options?.description ? (
              <DialogDescription className="text-[#646a73]">
                {options.description}
              </DialogDescription>
            ) : null}
          </DialogHeader>
          <DialogFooter className="gap-2">
            <Button
              variant="outline"
              className="border-[#e5e6eb] text-[#1f2329] hover:bg-[#f7f8fa]"
              onClick={() => resolveAndClose(false)}
            >
              {cancelText}
            </Button>
            <Button
              className={
                variant === "danger"
                  ? "bg-[#f53f3f] text-white hover:bg-[#d83232]"
                  : "bg-[#3370ff] text-white hover:bg-[#1e5eff]"
              }
              onClick={() => resolveAndClose(true)}
            >
              {confirmText}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </ConfirmContext.Provider>
  );
}

export function useConfirm() {
  const context = useContext(ConfirmContext);
  if (!context) {
    throw new Error("useConfirm must be used within ConfirmProvider");
  }
  return context;
}
