import { MouseEvent, useCallback, useEffect, useRef, useState } from 'react';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';

import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { useUserContext } from '../hooks';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { apiConfig } from '@/config/api.config';
import { Alert, KeenIcon, useDataGrid } from '@/components';
import { toast } from 'sonner';
import { useCallApi } from '@/hooks';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import clsx from 'clsx';

interface RoleListProps {
  id: string;
  name: string;
  roles: string;
  status: string;
}

interface CreateUserParams {
  email: string;
  username: string;
  password: string;
  retype_password: string;
  name: string;
  id_role: string;
  status: string;
}

const API_URL = apiConfig.service_dashboard;
type PasswordType = 'password' | 'retype_password';

const AddDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showAddDialog, handleAddDialog } = useUserContext();
  const { reload } = useDataGrid();
  const { PostData, GetData } = useCallApi();
  const [roles, setRoles] = useState<RoleListProps[]>([]);
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const initialState = {
    email: '',
    username: '',
    password: '',
    retype_password: '',
    name: '',
    id_role: '',
    status: ''
  };
  const [formField, setFormField] = useState(initialState);
  const [showPassword, setShowPassword] = useState({
    password: false,
    retype_password: false
  });

  const [messagePassword, setMessagePassword] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [passwordErrors, setPasswordErrors] = useState<string[]>([]);

  const validatePassword = (password: string, confirmPassword: string) => {
    const errors: string[] = [];

    if (password) {
      if (password.length < 8) {
        errors.push('Password must be at least 8 characters long');
      }
      if (!/[A-Z]/.test(password)) {
        errors.push('Password must contain at least one capital letter');
      }
      if (!/[0-9]/.test(password)) {
        errors.push('Password must contain at least one number');
      }
      if (!/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
        errors.push('Password must contain at least one special character');
      }
      if (password !== confirmPassword) {
        errors.push('Passwords do not match');
      }
    }

    return {
      isValid: errors.length === 0,
      errors
    };
  };

  const resetForm = () => {
    setFormField(initialState);
    setAlert({ show: false, message: '' });
  };

  /* actions */
  const doCreateUser = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();

      const response = await PostData(`${API_URL}/user/create`, formField);

      if (response?.status) {
        handleAddDialog(false);
        resetForm();
        reload();
        const createActivity = {
          module: 'Manage User',
          description: `Create New User => ${formField.username}`,
          action: 'C'
        };

        doSaveLogActivity(createActivity);
        toast.success('Success Create User');
      } else {
        toast.error('Failed to create user');
        setAlert({ show: true, message: 'Failed to create user. Please try again.' });
      }
    },
    [formField]
  );

  const fetchRoles = useCallback(async () => {
    const params = {
      limit: 100,
      page: 1,
      with_deleted: false,
      order_field: 'name',
      order_direction: 'ASC',
      filter: JSON.stringify({
        status: 'Y'
      })
    };
    const response = await GetData(`${API_URL}/user_role/list`, params);
    // console.log('ini data:', response);
    if (response?.status) {
      const roleList = response.data?.list || [];
      setRoles(roleList);
    } else {
      setRoles(() => []);
    }
    // console.log('ini data user_role:', response?.data);
  }, []);

  useEffect(() => {
    fetchRoles();
  }, [fetchRoles]);

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    console.log('Form data before submit:', formField);

    if (
      formField.email.trim() === '' ||
      formField.username.trim() === '' ||
      formField.password.trim() === '' ||
      formField.retype_password.trim() === '' ||
      formField.name.trim() === '' ||
      formField.id_role.trim() === '' ||
      formField.status.trim() === ''
    ) {
      setAlert({ show: true, message: 'Please fill name field.' });
      return;
    }

    doCreateUser(e);
    // console.log(formField);
    setAlert({ show: false, message: '' });
  };

  useEffect(() => {
    const validation = validatePassword(formField.password, formField.retype_password);
    setMessagePassword(validation.isValid);
    setPasswordErrors(validation.errors);
  }, [formField.password, formField.retype_password]);

  const isButtonDisabled = !messagePassword || isSubmitting || passwordErrors.length > 0;

  useEffect(() => {
    if (showAddDialog === false) {
      resetForm();
    }
  }, [showAddDialog]);

  const togglePassword = useCallback((event: MouseEvent<HTMLButtonElement>, key: string) => {
    event.preventDefault();
    setShowPassword((prev) => ({ ...prev, [key]: !prev[key as PasswordType] }));
  }, []);

  return (
    <Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}>
      <DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden [&>button]:hidden">
        <DialogHeader className="p-0 border-0">
          <DialogTitle></DialogTitle>
          <DialogDescription></DialogDescription>
          <div className="flex items-center justify-between flex-wrap grow">
            <div className="flex flex-col justify-center">
              <h1 className="text-xl font-semibold leading-none text-gray-900">User - Create</h1>
              <div className="flex items-center gap-2 text-sm font-normal text-gray-700"></div>
            </div>
            <div
              className="cursor-pointer hover:opacity-100 opacity-50"
              onClick={() => {
                handleAddDialog(false);
                resetForm();
              }}
            >
              <KeenIcon icon="cross" className="text-1.5xl" />
            </div>
          </div>
        </DialogHeader>
        <DialogBody className="scrollable-y px-0 pb-0" ref={parentRef}>
          <div className="flex flex-col px-0">
            {alert.show && (
              <Alert variant="danger" className="mb-3">
                <h3>{alert.message}</h3>
              </Alert>
            )}
            <form action="" onSubmit={handleSubmit}>
              <div className="card-body grid gap-5 p-0">
                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">Name</label>
                    <Input
                      className="input"
                      type="text"
                      autoComplete="off"
                      value={formField.name}
                      onChange={({ target }) =>
                        setFormField((prev) => ({ ...prev, name: target.value }))
                      }
                    />
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">Username</label>
                    <Input
                      className="input"
                      type="text"
                      autoComplete="off"
                      value={formField.username}
                      onChange={({ target }) =>
                        setFormField((prev) => ({ ...prev, username: target.value }))
                      }
                    />
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">Email</label>
                    <Input
                      className="input"
                      type="email"
                      autoComplete="off"
                      value={formField.email}
                      onChange={({ target }) =>
                        setFormField((prev) => ({ ...prev, email: target.value }))
                      }
                    />
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-center flex-wrap gap-2.5">
                    <label className="form-label max-w-56">Role</label>

                    <div className="grow">
                      <Select
                        value={formField.id_role}
                        onValueChange={(value) => {
                          console.log('Role selected:', value);
                          setFormField((prev) => ({ ...prev, id_role: value }));
                        }}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select" />
                        </SelectTrigger>
                        <SelectContent>
                          {roles.map((role, idx) => (
                            <SelectItem value={role.id} key={role.id}>
                              {role.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>

                <div className="flex items-center flex-wrap gap-2.5">
                  <label className="form-label max-w-56">Status</label>

                  <div className="grow">
                    <Select
                      value={formField.status}
                      onValueChange={(status) => setFormField((prev) => ({ ...prev, status }))}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Y">Active</SelectItem>
                        <SelectItem value="N">Non Active</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">Password</label>
                    <div className="input">
                      <input
                        className="form-control"
                        type={showPassword.password ? 'text' : 'password'}
                        value={formField.password}
                        onChange={({ target }) =>
                          setFormField((prev) => ({ ...prev, password: target.value }))
                        }
                      />
                      <button
                        className="btn btn-icon"
                        onClick={(e) => togglePassword(e, 'password')}
                      >
                        <KeenIcon
                          icon="eye"
                          className={clsx('text-gray-500', { hidden: showPassword.password })}
                        />
                        <KeenIcon
                          icon="eye-slash"
                          className={clsx('text-gray-500', {
                            hidden: !showPassword.password
                          })}
                        />
                      </button>
                    </div>
                  </div>
                </div>
                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Confirm Password
                    </label>
                    <div className="w-full">
                      <div className="input block">
                        <input
                          className="form-control"
                          autoComplete="off"
                          type={showPassword.retype_password ? 'text' : 'password'}
                          value={formField.retype_password}
                          onChange={({ target }) =>
                            setFormField((prev) => ({ ...prev, retype_password: target.value }))
                          }
                        />
                        <button
                          className="btn btn-icon"
                          onClick={(e) => togglePassword(e, 'retype_password')}
                        >
                          <KeenIcon
                            icon="eye"
                            className={clsx('text-gray-500', {
                              hidden: showPassword.retype_password
                            })}
                          />
                          <KeenIcon
                            icon="eye-slash"
                            className={clsx('text-gray-500', {
                              hidden: !showPassword.retype_password
                            })}
                          />
                        </button>
                      </div>
                      <div className="w-full">
                        {passwordErrors.length > 0 && (
                          <div className="text-xs text-red-500 mt-2">
                            {passwordErrors.map((error, index) => (
                              <p key={index}>{error}</p>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                </div>

                <div className="flex justify-end pt-2.5">
                  <Button className="btn btn-primary" type="submit" disabled={isButtonDisabled}>
                    Save Changes
                  </Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export { AddDialog };
