"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { Eye, EyeOff, Mail, Phone, Shield, User } from "lucide-react";
import {
  use,
  useCallback,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from "react";
import { useForm } from "react-hook-form";
import { userApi } from "~/api/user-api.service";
import Loader from "~/components/loader";
import { Button } from "~/components/ui/button";
import { Checkbox } from "~/components/ui/checkbox";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "~/components/ui/dialog";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "~/components/ui/form";
import { Input } from "~/components/ui/input";
import { ScrollArea } from "~/components/ui/scroll-area";
import { toBase64 } from "~/features/base64";
import { validateFile } from "~/features/file";
import RolesSelect from "../roles/roles-select";
import { AvatarUpload } from "./avartar-upload";
import { create } from "zustand";
import {
  removeNullishValues,
  removeUndefinedValues,
} from "~/features/remove-falsy-values";
import { APPROLE } from "~/types/enum";
import { usersSchema, type EmployeeFormData } from "~/lib/schema/users.schema";
import { omitKeys } from "~/features/object";
import z from "zod/v3";
import InputPassword from "~/components/input-password";
import { useMe } from "~/hooks/use-me";
import { useSelector } from "react-redux";
import type { RootState } from "~/store";
import { useAppDispatch } from "~/hooks/use-app-dispatch";

export interface UserModalState {
  open: boolean;
  data?: IUser;
  setOpen: (open: boolean) => void;
  setData: (data: IUser) => void;
  setEdit: (data: IUser) => void;
}

export const useUserModal = create<UserModalState>((set) => ({
  open: false,
  setOpen: (open) =>
    set((state) => ({ open, data: !open ? undefined : state.data })),
  setData: (data) => set({ data }),
  setEdit: (data) => set({ data, open: true }),
}));

export default function UserModal({
  children,
  onSubmited,
}: {
  children: ReactNode;
  onSubmited?: () => void;
}) {
  const { open, data, setOpen } = useUserModal();

  const { refetch } = useMe();
  const { user } = useSelector((state: RootState) => state.app);

  const form = useForm<EmployeeFormData>({
    resolver: zodResolver(usersSchema.getSchema(data)) as any,
    defaultValues: {
      email: "",
      username: "",
      first_name: "",
      last_name: "",
      phone: "",
      avatar: null,
      is_login_enabled: false,
      active: true,
      roles: [],
      password: "",
    },
  });

  const isLoginEnabled = form.watch("is_login_enabled");

  const isRoot = useMemo(() => {
    if (!data) return false;

    return data.roles.some((role) => role.role_key === APPROLE.ROOT);
  }, [data]);

  const onSubmit = useCallback(
    async (values: EmployeeFormData) => {
      const roles = values.roles.map((role) =>
        Number(role)
      ) as unknown as IRole[];

      if (!data) {
        const response = await userApi.create(
          removeNullishValues({ ...values, roles })
        );

        if (!response?.data) return;

        setOpen(false);
      } else {
        if (values?.avatar) {
          if (!z.string().url().safeParse(values.avatar).success) {
            const avatar = await toBase64(values.avatar);

            values.avatar = avatar;
          } else {
            delete values.avatar;
          }
        }

        const response = await userApi.update(
          data.id,
          omitKeys(
            removeUndefinedValues({
              ...values,
              roles,
              id: data.id,
            } as Partial<IUser>),
            ["email", "username"]
          )
        );

        if (!response?.data) return;

        setOpen(false);
      }

      form.reset({});
      onSubmited?.();

      if (user?.id === data?.id) {
        refetch();
      }
    },
    [data]
  );

  useEffect(() => {
    if (!data) return form.reset({});

    form.reset({ ...data, roles: data.roles.map((role) => String(role.id)) });
  }, [data]);

  return (
    <Dialog
      onOpenChange={(value) => {
        setOpen(value);
        form.reset({});
      }}
      open={open}
    >
      <DialogTrigger asChild>{children}</DialogTrigger>
      <DialogContent className="sm:max-w-4xl max-h-[90vh] p-0 flex flex-col">
        {/* Fixed Header */}
        <DialogHeader className="px-6 py-4 border-b">
          <DialogTitle className="flex items-center gap-2">
            <User className="h-5 w-5" />
            Thêm Nhân Viên Mới
          </DialogTitle>
          <DialogDescription>
            Điền thông tin chi tiết để thêm nhân viên mới vào hệ thống
          </DialogDescription>
        </DialogHeader>

        {/* Scrollable Content */}
        <ScrollArea className="h-[60vh]">
          <Form {...form}>
            <form className="space-y-6 px-6">
              {/* Avatar Upload */}
              <FormField
                control={form.control}
                name="avatar"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Ảnh đại diện</FormLabel>
                    <FormControl>
                      <AvatarUpload
                        value={field.value}
                        onChange={(file) => {
                          field.onChange(file);
                          // Trigger validation
                          form.trigger("avatar");
                        }}
                        error={form.formState.errors.avatar?.message as string}
                      />
                    </FormControl>
                    <FormDescription>
                      Tải lên ảnh đại diện cho nhân viên (tối đa 2MB)
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Personal Information */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="first_name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Họ *</FormLabel>
                      <FormControl>
                        <Input placeholder="Nhập họ" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="last_name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Tên *</FormLabel>
                      <FormControl>
                        <Input placeholder="Nhập tên" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              {/* Contact Information */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="email"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center gap-2">
                        <Mail className="h-4 w-4" />
                        Email *
                      </FormLabel>
                      <FormControl>
                        <Input
                          disabled={!!data}
                          type="email"
                          placeholder="example@company.com"
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="phone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center gap-2">
                        <Phone className="h-4 w-4" />
                        Số điện thoại
                      </FormLabel>
                      <FormControl>
                        <Input placeholder="0123456789" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              {/* Account Information */}
              <FormField
                control={form.control}
                name="username"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Tên đăng nhập *</FormLabel>
                    <FormControl>
                      <Input
                        disabled={!!data}
                        placeholder="Nhập tên đăng nhập"
                        {...field}
                      />
                    </FormControl>
                    <FormDescription>
                      Chỉ được chứa chữ cái, số và dấu gạch dưới
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Login Settings */}
              <div className="space-y-4">
                <FormField
                  control={form.control}
                  name="is_login_enabled"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                      <FormControl>
                        <Checkbox
                          disabled={isRoot}
                          checked={field.value}
                          onCheckedChange={field.onChange}
                        />
                      </FormControl>
                      <div className="space-y-1 leading-none">
                        <FormLabel>Cho phép đăng nhập</FormLabel>
                        <FormDescription>
                          Kích hoạt để nhân viên có thể đăng nhập vào hệ thống
                        </FormDescription>
                      </div>
                    </FormItem>
                  )}
                />

                {/* Password field - only show when login is enabled */}
                {isLoginEnabled && !isRoot && (
                  <FormField
                    control={form.control}
                    name="password"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Mật khẩu *</FormLabel>
                        <FormControl>
                          <div className="relative">
                            <InputPassword
                              placeholder="Nhập mật khẩu"
                              {...field}
                            />
                          </div>
                        </FormControl>
                        <FormDescription>
                          Mật khẩu phải có ít nhất 6 ký tự
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}

                <FormField
                  control={form.control}
                  name="active"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                      <FormControl>
                        <Checkbox
                          checked={field.value}
                          onCheckedChange={field.onChange}
                        />
                      </FormControl>
                      <div className="space-y-1 leading-none">
                        <FormLabel>Kích hoạt tài khoản</FormLabel>
                        <FormDescription>
                          Tài khoản sẽ được kích hoạt ngay sau khi tạo
                        </FormDescription>
                      </div>
                    </FormItem>
                  )}
                />
              </div>

              {/* Roles */}
              <FormField
                control={form.control}
                name="roles"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="flex items-center gap-2">
                      <Shield className="h-4 w-4" />
                      Vai trò
                    </FormLabel>
                    <FormControl>
                      <RolesSelect
                        showRoot={isRoot}
                        disabled={data?.roles?.some(
                          (role) => role.role_key === APPROLE.ROOT
                        )}
                        {...field}
                        defaultValue={field?.value?.map((item) => String(item))}
                        onValueChange={field.onChange}
                      />
                    </FormControl>
                    <FormDescription>
                      Chọn vai trò cho nhân viên trong hệ thống
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </form>
          </Form>
        </ScrollArea>

        {/* Fixed Footer */}
        <DialogFooter className="px-6 py-4 border-t">
          <div className="flex justify-end gap-4">
            <DialogClose asChild>
              <Button variant={"outline"}>Hủy</Button>
            </DialogClose>
            <Button
              onClick={form.handleSubmit(onSubmit)}
              type="submit"
              disabled={form.formState.isSubmitting}
            >
              {form.formState.isSubmitting ? (
                <Loader color="white" />
              ) : data ? (
                "Cập nhật"
              ) : (
                "Thêm Nhân Viên"
              )}
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
