"use client";

import { Button } from "@/shared/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/ui/dialog";
import { Input } from "@/shared/ui/input";
import { Auth_Api } from "@/widgets/welcome/lib/data";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { Loader2 } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

interface EditDialogProps {
  open: boolean;
  onClose: () => void;
  user: {
    id: number;
    first_name: string;
    last_name: string;
  };
}

export function EditDialog({ open, onClose, user }: EditDialogProps) {
  const [firstName, setFirstName] = useState(user.first_name);
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const [lastName, setLastName] = useState(user.last_name);

  const { mutate, isPending } = useMutation({
    mutationFn: ({
      first_name,
      last_name,
    }: {
      first_name: string;
      last_name: string;
    }) => {
      return Auth_Api.updateUser({ first_name, last_name });
    },
    onSuccess() {
      queryClient.resetQueries({ queryKey: ["get_me"] });
      onClose();
    },
    onError(error: AxiosError<{ non_field_errors: [string] }>) {
      toast.error(t("Xatolik yuz berdi"), {
        icon: null,
        description: error.name,
        position: "bottom-right",
      });
    },
  });

  const handleSave = async () => {
    mutate({
      first_name: firstName,
      last_name: lastName,
    });
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[425px] rounded-2xl">
        <DialogHeader>
          <DialogTitle>{t("Tahrirlash")}</DialogTitle>
          <DialogDescription>
            {t(
              "Update your personal information below and click save when done.",
            )}
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-4 py-4">
          <div className="grid gap-2">
            <label className="text-sm font-medium text-gray-200">
              {t("First Name")}
            </label>
            <Input
              value={firstName}
              onChange={(e) => setFirstName(e.target.value)}
              placeholder={t("First Name")}
            />
          </div>
          <div className="grid gap-2">
            <label className="text-sm font-medium text-gray-200">
              {t("Last Name")}
            </label>
            <Input
              value={lastName}
              onChange={(e) => setLastName(e.target.value)}
              placeholder={t("Last Name")}
            />
          </div>
        </div>

        <DialogFooter className="flex justify-end gap-2">
          <Button variant="outline" onClick={onClose}>
            {t("Bekor qilish")}
          </Button>
          <Button onClick={handleSave}>
            {isPending ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              </>
            ) : (
              t("Saqlash")
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
