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 {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from '@/components/ui/command';
import { ChevronDown } from 'lucide-react';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
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';

export interface CustomerProps {
  id: string;
  msisdn: string;
  email: string;
  fullname: string;
  username: string;
}

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_CUSTOMER = apiConfig.service_customer;
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: '',
    customerid: ''
  };
  const [formField, setFormField] = useState(initialState);
  const [showPassword, setShowPassword] = useState({
    password: false,
    retype_password: false
  });

  const [messagePassword, setMessagePassword] = useState(true);
  const [open, setOpen] = useState(false);
  const [customers, setCustomers] = useState<CustomerProps[]>([]);
  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);
  }, []);

  const getCustomerList = async (sorting: any) => {
    try {
      sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
      const response = await GetData(`${API_URL_CUSTOMER}/customer/list`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
      });

      setCustomers(response?.data.list);
    } catch (error) {
      console.error('Error fetching customer', error);
    }
  };

  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() === '' ||
      formField.customerid.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]);

  useEffect(() => {
    getCustomerList([{ id: 'id', desc: false }]);
  }, []);

  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">Customer</label>
                    <Popover open={open} onOpenChange={setOpen}>
                      <PopoverTrigger asChild>
                        <button
                          type="button"
                          className="input col-span-5 text-left flex justify-between"
                          style={{ color: 'inherit' }}
                        >
                          <span>
                            {customers.find((customer) => customer.id === formField.customerid)
                              ?.username || 'Select Customer'}
                          </span>
                          <ChevronDown className="w-4 h-4 opacity-70" />
                        </button>
                      </PopoverTrigger>
                      <PopoverContent className="w-[400px] p-0">
                        <Command>
                          <CommandInput placeholder="Search Customer..." />
                          <CommandList
                            className="max-h-[300px] overflow-y-auto"
                            style={{ touchAction: 'pan-y' }}
                            onWheel={(e) => {
                              e.currentTarget.scrollTop += e.deltaY;
                            }}
                          >
                            <CommandEmpty>No Customer found.</CommandEmpty>
                            <CommandGroup>
                              {customers.map((customer) => (
                                <CommandItem
                                  key={customer.id}
                                  value={customer.username}
                                  onSelect={() => {
                                    setFormField({
                                      ...formField,
                                      customerid: customer.id
                                    });
                                    setOpen(false);
                                  }}
                                >
                                  {customer.username}
                                </CommandItem>
                              ))}
                            </CommandGroup>
                          </CommandList>
                        </Command>
                      </PopoverContent>
                    </Popover>
                  </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={(id_role) => {
                          setTimeout(() => {
                            setFormField((prev) => ({ ...prev, id_role }));
                          }, 0);
                          // console.log('Role selected:', 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) => {
                        setTimeout(() => {
                          setFormField((prev) => ({ ...prev, status }));
                        }, 0);
                      }}
                    >
                      <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 };
