"use client";

import { useRouter } from "@/i18n/routing";
import { zodResolver } from "@hookform/resolvers/zod";
import { Camera, Eye, EyeOff, RefreshCw } from "lucide-react";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import * as z from "zod";

import { UnifiedFileUploader } from "@/components/shared/unified-file-uploader";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { PhoneInput } from "@/components/ui/phone-input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  useRoles,
  useUserMutations,
  type CreateUserRequest,
  type UpdateUserRequest,
} from "@/hooks/use-users";
import type { User } from "@/lib/api/types";

interface UserFormProps {
  user?: User; // If provided, form is in edit mode
  onSuccess?: () => void;
  onCancel?: () => void;
}

export function UserForm({ user, onSuccess, onCancel }: UserFormProps) {
  const t = useTranslations();
  const router = useRouter();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const [avatarPreview, setAvatarPreview] = useState<string | null>(
    user?.avatar || null,
  );
  const [showPassword, setShowPassword] = useState(false);
  const [showPasswordConfirmation, setShowPasswordConfirmation] =
    useState(false);
  const isEditMode = !!user;

  // Fetch roles from API
  const { data: rolesData, isLoading: rolesLoading } = useRoles();
  const roles = rolesData?.data?.roles || [];

  // User mutations
  const { createUser, updateUser } = useUserMutations();

  // Helper to format phone number to E.164 format
  const formatPhoneToE164 = (phone: string | null | undefined): string => {
    if (!phone) return "";

    // If already in E.164 format (starts with +), return as is
    if (phone.startsWith("+")) return phone;

    // Remove all spaces and dashes
    const cleaned = phone.replace(/[\s-]/g, "");

    // If starts with 0 (local format), remove it and add +966 (Saudi Arabia)
    if (cleaned.startsWith("0")) {
      return `+966${cleaned.substring(1)}`;
    }

    // If doesn't start with + or 0, assume it's already without country code
    return `+966${cleaned}`;
  };

  // Define form schema with translated validation messages
  const formSchema = useMemo(
    () =>
      z
        .object({
          name: z.string().min(3, {
            message: t("users.form.validation.nameMin"),
          }),
          email: z.string().email(t("users.form.validation.emailInvalid")),
          phone: z.string().min(9, {
            message: t("users.form.validation.phoneMin"),
          }),
          password: isEditMode
            ? z.string().optional()
            : z.string().min(8, {
                message: t("users.form.validation.passwordMin"),
              }),
          password_confirmation: isEditMode
            ? z.string().optional()
            : z.string().min(8, {
                message: t("users.form.validation.passwordMin"),
              }),
          role_id: z.string().min(1, {
            message: t("users.form.validation.roleRequired"),
          }),
        })
        .refine(
          (data) => {
            // Only validate password match if password is provided
            if (data.password || data.password_confirmation) {
              return data.password === data.password_confirmation;
            }
            return true;
          },
          {
            message: t("users.form.validation.passwordMismatch"),
            path: ["password_confirmation"],
          },
        ),
    [t, isEditMode],
  );

  // Initialize form with react-hook-form
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: user?.name || "",
      email: user?.email || "",
      phone: formatPhoneToE164(user?.phone),
      password: "",
      password_confirmation: "",
      role_id: user?.roles?.[0]?.id?.toString() || "",
    },
  });

  // Generate random password
  const generatePassword = () => {
    const length = 12;
    const charset =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
    let password = "";
    for (let i = 0; i < length; i++) {
      password += charset.charAt(Math.floor(Math.random() * charset.length));
    }

    // Set both password fields
    form.setValue("password", password);
    form.setValue("password_confirmation", password);

    // Show success message
    toast.success(
      t("users.form.passwordGenerated") || "Password generated successfully",
    );
  };

  const handleAvatarChange = (files: File[]) => {
    const file = files[0];
    if (file) {
      // Validate file size (max 5MB)
      if (file.size > 5 * 1024 * 1024) {
        toast.error(t("users.form.validation.avatarSize"));
        return;
      }

      // Validate file type
      if (!file.type.startsWith("image/")) {
        toast.error(t("users.form.validation.avatarType"));
        return;
      }

      setAvatarFile(file);
      const reader = new FileReader();
      reader.onloadend = () => {
        setAvatarPreview(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleCancel = () => {
    if (onCancel) {
      onCancel();
    } else {
      router.push("/users");
    }
  };

  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    setIsSubmitting(true);
    try {
      if (isEditMode && user) {
        // Update mode - password is optional
        const updatePayload: UpdateUserRequest = {
          name: values.name,
          email: values.email,
          phone: values.phone,
          roles: [parseInt(values.role_id)],
          avatar: avatarFile,
        };

        // Only include password if provided
        if (values.password) {
          updatePayload.password = values.password;
          updatePayload.password_confirmation = values.password_confirmation;
        }

        await updateUser(user.id, updatePayload);
        // Success toast is handled by the hook with backend message
      } else {
        // Create mode - password is required
        const createPayload: CreateUserRequest = {
          name: values.name,
          email: values.email,
          phone: values.phone,
          roles: [parseInt(values.role_id)],
          avatar: avatarFile,
          password: values.password!, // Non-null assertion - validated by Zod
          password_confirmation: values.password_confirmation!,
        };

        await createUser(createPayload);
        // Success toast is handled by the hook with backend message
      }

      if (onSuccess) {
        onSuccess();
      } else {
        router.push("/users");
      }
    } catch {
      // Error toast is handled by the hook with backend message
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)}>
        <Card className="overflow-hidden">
          {/* Header */}
          <CardHeader className="border-b ">
            <h2 className="text-base font-semibold text-foreground">
              {isEditMode
                ? t("users.form.editTitle")
                : t("users.form.createTitle")}
            </h2>
          </CardHeader>

          {/* Form Content */}
          <CardContent className="p-6 space-y-6">
            {/* Profile Picture Section */}
            <div className="flex w-full items-center justify-center">
              <div className="relative">
                <div className="bg-muted border border-border rounded-full p-4 flex items-center justify-center size-28 sm:size-32 overflow-hidden">
                  {avatarPreview ? (
                    <Image
                      src={avatarPreview}
                      alt="Avatar"
                      width={128}
                      height={128}
                      className="object-cover w-full h-full"
                    />
                  ) : (
                    <Image
                      src="/profile-placeholder.svg"
                      alt="Default avatar"
                      width={128}
                      height={128}
                      className="object-contain w-full h-full"
                    />
                  )}
                </div>
                <UnifiedFileUploader
                  mode="trigger"
                  onChange={handleAvatarChange}
                  multiple={false}
                  accept="image/*"
                  useGlobalSettings={false}
                  maxSizeMb={5}
                  labels={{ browseText: t("common.browseFiles") }}
                  className="absolute bottom-0 right-0"
                  triggerContent={
                    <button
                      type="button"
                      className="size-10 cursor-pointer rounded-full bg-primary transition-colors hover:bg-primary/90 flex items-center justify-center"
                    >
                      <Camera className="size-5 text-primary-foreground" />
                    </button>
                  }
                />
              </div>
            </div>

            {/* Form Fields Row 1: Username + Role */}
            <div className="grid w-full gap-4 md:grid-cols-2">
              {/* Username Field */}
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem className="flex-1">
                    <FormLabel className="text-sm text-foreground flex gap-1">
                      <span className="text-destructive">*</span>
                      <span>{t("users.form.name")}</span>
                    </FormLabel>
                    <FormControl>
                      <Input
                        type="text"
                        placeholder={t("users.form.namePlaceholder")}
                        className="h-10"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Role Field */}
              <FormField
                control={form.control}
                name="role_id"
                render={({ field }) => (
                  <FormItem className="flex-1">
                    <FormLabel className="text-sm text-foreground flex gap-1">
                      <span className="text-destructive">*</span>
                      <span>{t("users.form.role")}</span>
                    </FormLabel>
                    <Select
                      onValueChange={field.onChange}
                      defaultValue={field.value}
                    >
                      <FormControl>
                        <SelectTrigger className="h-10 w-full">
                          <SelectValue
                            placeholder={t("users.form.rolePlaceholder")}
                          />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {rolesLoading ? (
                          <div className="py-2 px-3 text-sm text-muted-foreground">
                            Loading roles...
                          </div>
                        ) : roles.length === 0 ? (
                          <div className="py-2 px-3 text-sm text-destructive">
                            No roles available
                          </div>
                        ) : (
                          roles.map((role) => (
                            <SelectItem
                              key={role.id}
                              value={role.id.toString()}
                            >
                              {role.label}
                            </SelectItem>
                          ))
                        )}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Form Fields Row 2: Email + Phone */}
            <div className="grid w-full gap-4 md:grid-cols-2">
              {/* Email Field */}
              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem className="flex-1">
                    <FormLabel className="text-sm text-foreground flex gap-1">
                      <span className="text-destructive">*</span>
                      <span>{t("users.form.email")}</span>
                    </FormLabel>
                    <FormControl>
                      <Input
                        type="email"
                        placeholder={t("users.form.emailPlaceholder")}
                        className="h-10"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Phone Field */}
              <FormField
                control={form.control}
                name="phone"
                render={({ field }) => (
                  <FormItem className="flex-1">
                    <FormLabel className="text-sm text-foreground flex gap-1">
                      <span className="text-destructive">*</span>
                      <span>{t("users.form.phone")}</span>
                    </FormLabel>
                    <FormControl>
                      <PhoneInput
                        placeholder={t("users.form.phonePlaceholder")}
                        defaultCountry="SA"
                        className="[&_button]:rounded-s [&_input]:rounded-e"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Form Fields Row 3: Password + Confirm Password */}
            <div className="grid w-full gap-4 md:grid-cols-2">
              {/* Password Field */}
              <FormField
                control={form.control}
                name="password"
                render={({ field }) => (
                  <FormItem className="flex-1">
                    <FormLabel className="text-sm text-foreground flex gap-1 items-center justify-between w-full">
                      <div className="flex flex-wrap items-center gap-1">
                        {!isEditMode && (
                          <span className="text-destructive">*</span>
                        )}
                        <span>{t("users.form.password")}</span>
                        {isEditMode && (
                          <span className="text-muted-foreground text-xs font-normal">
                            ({t("users.form.optional")})
                          </span>
                        )}
                      </div>
                      <Button
                        type="button"
                        variant="outline"
                        size="icon"
                        className="h-8 w-8 shrink-0 p-0 text-primary"
                        onClick={generatePassword}
                      >
                        <RefreshCw className="size-4" />
                        {/* <span>{t("users.form.generatePassword") || "Generate"}</span> */}
                      </Button>
                    </FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          type={showPassword ? "text" : "password"}
                          placeholder={t("users.form.passwordPlaceholder")}
                          className="h-10 "
                          {...field}
                        />
                        <button
                          type="button"
                          onClick={() => setShowPassword(!showPassword)}
                          className="absolute inset-y-0 end-0 flex items-center pe-3 text-muted-foreground hover:text-foreground transition-colors"
                        >
                          {showPassword ? (
                            <EyeOff className="h-4 w-4" />
                          ) : (
                            <Eye className="h-4 w-4" />
                          )}
                        </button>
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Password Confirmation Field */}
              <FormField
                control={form.control}
                name="password_confirmation"
                render={({ field }) => (
                  <FormItem className="flex-1">
                    <FormLabel className="text-sm text-foreground flex gap-1">
                      {!isEditMode && (
                        <span className="text-destructive">*</span>
                      )}
                      <span>{t("users.form.passwordConfirmation")}</span>
                      {isEditMode && (
                        <span className="text-muted-foreground text-xs font-normal">
                          ({t("users.form.optional")})
                        </span>
                      )}
                    </FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          type={showPasswordConfirmation ? "text" : "password"}
                          placeholder={t(
                            "users.form.passwordConfirmationPlaceholder",
                          )}
                          className="h-10 "
                          {...field}
                        />
                        <button
                          type="button"
                          onClick={() =>
                            setShowPasswordConfirmation(
                              !showPasswordConfirmation,
                            )
                          }
                          className="absolute inset-y-0 end-0 flex items-center pe-3 text-muted-foreground hover:text-foreground transition-colors"
                        >
                          {showPasswordConfirmation ? (
                            <EyeOff className="h-4 w-4" />
                          ) : (
                            <Eye className="h-4 w-4" />
                          )}
                        </button>
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Divider */}
            <div className="border-t border-border" />

            {/* Action Buttons */}
            <div className="flex flex-col gap-3 sm:flex-row">
              <Button
                type="button"
                variant="outline"
                className="h-10 w-full sm:w-auto"
                onClick={handleCancel}
                disabled={isSubmitting}
              >
                {t("users.form.cancel")}
              </Button>
              <Button
                type="submit"
                variant="default"
                className="h-10 w-full sm:w-auto"
                disabled={isSubmitting}
              >
                {isSubmitting
                  ? t("users.form.submitting")
                  : isEditMode
                    ? t("users.form.update")
                    : t("users.form.submit")}
              </Button>
            </div>
          </CardContent>
        </Card>
      </form>
    </Form>
  );
}
