'use client';

import { useEffect, useState } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { Eye, EyeOff } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useLanguage } from '@/providers/i18n-provider';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { getUserFormSchema, UserFormType } from '../schemas/user-form-schema';

interface IUser {
  id: string;
  employeeName: string;
  email: string;
  phone: string;
  roles: string[];
  avatar?: string;
}

interface AddUserModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  user: IUser | null;
  onSave: (user: IUser) => void;
}

const availableRoles = ['admin', 'manager', 'engineer', 'accountant'];

export function AddUserModal({
  open,
  onOpenChange,
  user,
  onSave,
}: AddUserModalProps) {
  const { t } = useTranslation();
  const { dir } = useLanguage();
  const [passwordVisible, setPasswordVisible] = useState(false);

  const form = useForm<UserFormType>({
    resolver: zodResolver(getUserFormSchema(t)),
    defaultValues: {
      employeeName: '',
      email: '',
      password: '',
      phone: '',
      roles: [],
    },
  });

  // Update form when user changes (for editing)
  useEffect(() => {
    if (user) {
      form.reset({
        employeeName: user.employeeName,
        email: user.email,
        password: '',
        phone: user.phone,
        roles: user.roles,
      });
    } else {
      form.reset({
        employeeName: '',
        email: '',
        password: '',
        phone: '',
        roles: [],
      });
    }
  }, [user, form]);

  const onSubmit = (values: UserFormType) => {
    const userData: IUser = {
      id: user?.id || '',
      employeeName: values.employeeName,
      email: values.email,
      phone: values.phone,
      roles: values.roles,
      avatar: user?.avatar,
    };
    onSave(userData);
    form.reset();
  };

  const handleRoleToggle = (role: string, checked: boolean) => {
    const currentRoles = form.getValues('roles');
    if (checked) {
      form.setValue('roles', [...currentRoles, role]);
    } else {
      form.setValue(
        'roles',
        currentRoles.filter((r) => r !== role),
      );
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent
        className=" max-w-[340px] w-full rounded-2xl  sm:max-w-[500px]"
        dir={dir}
      >
        <DialogHeader>
          <DialogTitle>
            {user ? t('admin.updateUser') : t('admin.addUser')}
          </DialogTitle>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            {/* Employee Name */}
            <FormField
              control={form.control}
              name="employeeName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t('admin.form.employeeName')}</FormLabel>
                  <FormControl>
                    <Input
                      placeholder={t('admin.placeholders.employeeName')}
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Email */}
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t('admin.form.email')}</FormLabel>
                  <FormControl>
                    <Input
                      type="email"
                      placeholder={t('admin.placeholders.email')}
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Password */}
            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t('admin.form.password')}</FormLabel>
                  <div className="relative">
                    <Input
                      type={passwordVisible ? 'text' : 'password'}
                      placeholder={t('admin.placeholders.password')}
                      {...field}
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      mode="icon"
                      size="sm"
                      onClick={() => setPasswordVisible(!passwordVisible)}
                      className="absolute end-0 top-1/2 -translate-y-1/2 h-7 w-7 me-1.5 bg-transparent!"
                      aria-label={
                        passwordVisible ? 'Hide password' : 'Show password'
                      }
                    >
                      {passwordVisible ? (
                        <EyeOff className="text-muted-foreground" />
                      ) : (
                        <Eye className="text-muted-foreground" />
                      )}
                    </Button>
                  </div>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Phone Number */}
            <FormField
              control={form.control}
              name="phone"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t('admin.form.phone')}</FormLabel>
                  <FormControl>
                    <Input
                      placeholder={t('admin.placeholders.phone')}
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Roles */}
            <FormField
              control={form.control}
              name="roles"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t('admin.form.roles')}</FormLabel>
                  <div className="border rounded-lg p-4 bg-muted/20 space-y-3">
                    {availableRoles.map((role) => (
                      <div key={role} className="flex items-center gap-2">
                        <Checkbox
                          id={`role-${role}`}
                          checked={field.value.includes(role)}
                          onCheckedChange={(checked) =>
                            handleRoleToggle(role, checked === true)
                          }
                        />
                        <Label
                          htmlFor={`role-${role}`}
                          className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                        >
                          {t(`admin.roles.${role}`)}
                        </Label>
                      </div>
                    ))}
                  </div>
                  <FormMessage />
                </FormItem>
              )}
            />

            <DialogFooter className="flex gap-2 sm:gap-0">
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
              >
                {t('admin.form.cancel')}
              </Button>
              <Button type="submit">{t('admin.form.submit')}</Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
