"use client";

import { Button, VStack, Input } from "@chakra-ui/react";
import {
  DialogRoot,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogBody,
  DialogFooter,
  DialogCloseTrigger,
} from "@/components/ui/overlays/dialog";
import { Field } from "@/components/ui/forms/field";
import {
  NativeSelectRoot,
  NativeSelectField,
} from "@/components/ui/forms/native-select";
import { Switch } from "@/components/ui/forms/switch";
import { useTranslations } from "next-intl";
import { AdminUserDto } from "@/lib/api/admin/types";
import { useState } from "react";
import {
  useUpdateUserRole,
  useUpdateUserSubscription,
  useToggleUserActive,
} from "@/lib/api/admin/use-hooks";

interface EditUserModalProps {
  user: AdminUserDto | null;
  isOpen: boolean;
  onClose: () => void;
}

export function EditUserModal({ user, isOpen, onClose }: EditUserModalProps) {
  if (!user) return null;

  return (
    <EditUserModalContent
      key={user.id}
      user={user}
      isOpen={isOpen}
      onClose={onClose}
    />
  );
}

function formatDateInputValue(value?: string | null): string {
  if (!value) return "";
  try {
    return new Date(value).toISOString().split("T")[0];
  } catch {
    return "";
  }
}

function EditUserModalContent({
  user,
  isOpen,
  onClose,
}: {
  user: AdminUserDto;
  isOpen: boolean;
  onClose: () => void;
}) {
  const t = useTranslations("admin");
  const tCommon = useTranslations("common");

  const [role, setRole] = useState(user.role || "user");
  const [plan, setPlan] = useState(user.subscriptionStatus || "free");
  const [expiresAt, setExpiresAt] = useState<string>(
    formatDateInputValue(user.subscriptionExpiresAt),
  );
  const [isActive, setIsActive] = useState(user.isActive);

  const { mutateAsync: updateRole, isPending: rolePending } =
    useUpdateUserRole();
  const { mutateAsync: updateSub, isPending: subPending } =
    useUpdateUserSubscription();
  const { mutateAsync: toggleActive, isPending: togglePending } =
    useToggleUserActive();

  const handleSave = async () => {
    try {
      if (role !== user.role) {
        await updateRole({ id: user.id, dto: { role } });
      }

      const currentExpiresAtStr = user.subscriptionExpiresAt
        ? new Date(user.subscriptionExpiresAt).toISOString().split("T")[0]
        : "";

      if (
        plan !== user.subscriptionStatus ||
        expiresAt !== currentExpiresAtStr
      ) {
        await updateSub({
          id: user.id,
          dto: {
            plan,
            expiresAt: expiresAt ? new Date(expiresAt).toISOString() : null,
          },
        });
      }
      if (isActive !== user.isActive) {
        await toggleActive(user.id);
      }
      onClose();
    } catch (error) {
      console.error(error);
    }
  };

  const isPending = rolePending || subPending || togglePending;

  return (
    <DialogRoot open={isOpen} onOpenChange={(e) => !e.open && onClose()}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>
            {t("edit-user-title", { email: user.email })}
          </DialogTitle>
        </DialogHeader>
        <DialogBody>
          <VStack gap={4} align="stretch">
            <Field label={t("user-role-field")}>
              <NativeSelectRoot>
                <NativeSelectField
                  value={role}
                  onChange={(e) => setRole(e.target.value)}
                  items={[
                    { label: t("standard-user"), value: "user" },
                    { label: t("superadmin"), value: "superadmin" },
                  ]}
                />
              </NativeSelectRoot>
            </Field>

            <Field label={t("subscription-plan-field")}>
              <NativeSelectRoot>
                <NativeSelectField
                  value={plan}
                  onChange={(e) => {
                    const newPlan = e.target.value;
                    setPlan(newPlan);
                    if (
                      (newPlan === "premium" || newPlan === "plus") &&
                      !expiresAt
                    ) {
                      const d = new Date();
                      d.setDate(d.getDate() + 30);
                      setExpiresAt(d.toISOString().split("T")[0]);
                    } else if (
                      newPlan === "free" ||
                      newPlan === "cancelled" ||
                      newPlan === "past_due"
                    ) {
                      setExpiresAt("");
                    }
                  }}
                  items={[
                    { label: t("plan-free"), value: "free" },
                    { label: t("plan-plus"), value: "plus" },
                    { label: t("plan-premium"), value: "premium" },
                    { label: t("plan-past-due"), value: "past_due" },
                    { label: t("plan-cancelled"), value: "cancelled" },
                  ]}
                />
              </NativeSelectRoot>
            </Field>

            {plan !== "free" && (
              <Field label={t("subscription-end-date")}>
                <Input
                  type="date"
                  value={expiresAt}
                  onChange={(e) => setExpiresAt(e.target.value)}
                />
              </Field>
            )}

            <Field label={t("account-active-question")}>
              <Switch
                checked={isActive}
                onCheckedChange={(e) => setIsActive(e.checked)}
              >
                {isActive ? tCommon("active") : tCommon("inactive")}
              </Switch>
            </Field>
          </VStack>
        </DialogBody>
        <DialogFooter>
          <Button variant="outline" onClick={onClose} disabled={isPending}>
            {tCommon("cancel")}
          </Button>
          <Button
            colorPalette="primary"
            onClick={handleSave}
            loading={isPending}
          >
            {tCommon("save")}
          </Button>
        </DialogFooter>
        <DialogCloseTrigger />
      </DialogContent>
    </DialogRoot>
  );
}
