import { useCallback, useEffect, useRef, useState } from 'react';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { useUserContext } from '../hooks';
import { ChevronDown } from 'lucide-react';
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 {
  CustomerProps,
  initialStateCreateUser,
  RoleListProps,
  validateFormCreateUser
} from './Types';

const API_URL_CUSTOMER = apiConfig.service_customer;
const API_URL = apiConfig.service_dashboard;

const EditDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showEditDialog, selectedUser, handleEditDialog } = useUserContext();
  const { reload } = useDataGrid();
  const { GetData, PutData } = useCallApi();
  const [open, setOpen] = useState(false);
  const [roles, setRoles] = useState<RoleListProps[]>([]);
  const [customers, setCustomers] = useState<CustomerProps[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isFetching, setIsFetching] = useState(false);

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCustomerName, setSelectedCustomerName] = useState('');
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [isLoadingCustomer, setIsLoadingCustomer] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const [formField, setFormField] = useState(initialStateCreateUser);

  const resetForm = () => {
    setFormField(initialStateCreateUser);
    setSelectedCustomerName('');
    setSearchTerm('');
    setErrors({});
  };

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

      if (!validateFormCreateUser(formField, setErrors, 'update')) {
        setIsSubmitting(false);
        return;
      }

      try {
        const response = await PutData(`${API_URL}/user/update/${selectedUser}`, {
          ...formField
        });

        if (response?.status) {
          resetForm();
          handleEditDialog(false, null);
          toast.success('Success Update User');
          reload();
          const createActivity = {
            module: 'Manage User',
            description: `Edit User => ${formField.username}`,
            action: 'U'
          };

          doSaveLogActivity(createActivity);
        } else {
          toast.error(response?.message);
        }
      } catch (error) {
        toast.error('Something went wrong, please try again.');
      } finally {
        setIsSubmitting(false);
      }
    },
    [selectedUser, formField]
  );

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

      setRoles(response?.data.list);
    } catch (error) {
      console.error('Error fetching role', error);
    }
  }, []);

  const getCustomerList = async (sorting: any, filterValue: string) => {
    const filter: any =
      filterValue?.trim().length === 0 ? {} : { fullname: { like: `%${filterValue}%` } };

    sorting = sorting.length == 0 ? [{ id: 'created_at', desc: false }] : sorting;

    const query: any = {
      limit: 100,
      page: 1,
      with_deleted: false,
      order_field: sorting[0].id,
      order_direction: sorting[0].desc ? 'DESC' : 'ASC'
    };

    if (filter && Object.keys(filter).length > 0) {
      query.filter = JSON.stringify(filter);
    }
    try {
      const response = await GetData(`${API_URL_CUSTOMER}/customer/list`, query);

      if (response?.status) {
        setCustomers(response?.data.list);
      } else {
        toast.error(response?.message);
      }
    } catch (error) {
      toast.error('Failed to fetch customer list');
    } finally {
      setIsLoadingCustomer(false);
    }
  };

  const doFetchUserData = useCallback(async (id: string) => {
    setIsFetching(true);

    const response = await GetData(`${API_URL}/user/detail/${id}`, { id });

    if (response?.status) {
      setFormField((prev) => ({
        ...prev,
        name: response.data.name,
        username: response.data.username,
        email: response.data.email,
        id_role: response.data.idRole,
        status: response.data.status,
        customerid: response.data.customer?.id || ''
      }));
    } else {
      setFormField((prev) => ({
        ...prev,
        name: '',
        username: '',
        email: '',
        id_role: '',
        status: '',
        customerid: ''
      }));
    }
    setIsFetching(false);
  }, []);

  const handleCustomerSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setIsLoadingCustomer(true);
    setSearchTerm(e.target.value);
    setSelectedCustomerName(e.target.value);
    setDropdownOpen(true);
    const timer = setTimeout(() => {
      getCustomerList([{ id: 'fullname', desc: false }], e.target.value);
    }, 500);
    return () => clearTimeout(timer);
  };

  const handleCustomerSelect = (customer: CustomerProps) => {
    setFormField({ ...formField, customerid: customer.id });
    setSelectedCustomerName(customer.fullname);
    setDropdownOpen(false);
  };

  const filteredCustomer = customers
    .filter((item) => item.fullname.toLowerCase().includes(searchTerm.toLowerCase()))
    .slice(0, 10);

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

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

  useEffect(() => {
    if (selectedUser) {
      doFetchUserData(selectedUser);
    }
  }, [selectedUser]);

  useEffect(() => {
    const handleClickOutside = (event: any) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setDropdownOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  return (
    <Dialog open={showEditDialog} onOpenChange={(open) => handleEditDialog(open, null)}>
      <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 - Update</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={() => handleEditDialog(false, null)}
            >
              <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">
            {isFetching ? (
              <div className="flex flex-col items-center justify-center p-8">
                <div className="animate-pulse flex space-x-4 w-full">
                  <div className="flex-1 space-y-4 py-1">
                    <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                    <div className="space-y-2">
                      <div className="h-4 bg-gray-200 rounded"></div>
                      <div className="h-4 bg-gray-200 rounded w-5/6"></div>
                    </div>
                  </div>
                </div>
                <p className="mt-4 text-gray-500">Loading User Details...</p>
              </div>
            ) : (
              <form onSubmit={doUpdateUser}>
                <div className="card-body grid gap-5 p-0">
                  <div className="flex gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">Name</label>
                    <div className="grow flex flex-col">
                      <Input
                        className={`input ${errors.name ? 'border-red-500' : ''}`}
                        type="text"
                        autoComplete="off"
                        value={formField.name}
                        onChange={({ target }) => {
                          setFormField((prev) => ({ ...prev, name: target.value }));
                          setErrors((prev) => ({ ...prev, name: '' }));
                        }}
                      />
                      {errors.name && (
                        <span className="text-red-500 text-xs mt-1">{errors.name}</span>
                      )}
                    </div>
                  </div>

                  {/* Username */}
                  <div className="flex gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">Username</label>
                    <div className="grow flex flex-col">
                      <Input
                        className={`input ${errors.username ? 'border-red-500' : ''}`}
                        type="text"
                        autoComplete="off"
                        value={formField.username}
                        onChange={({ target }) => {
                          setFormField((prev) => ({ ...prev, username: target.value }));
                          setErrors((prev) => ({ ...prev, username: '' }));
                        }}
                      />
                      {errors.username && (
                        <span className="text-red-500 text-xs mt-1">{errors.username}</span>
                      )}
                    </div>
                  </div>

                  {/* Customer */}
                  <div className="flex gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">Customer</label>
                    <div className="grow flex flex-col" ref={dropdownRef}>
                      <Input
                        id="customer"
                        type="text"
                        value={selectedCustomerName || searchTerm}
                        onChange={handleCustomerSearch}
                        placeholder="Search Customer"
                        onClick={() => setDropdownOpen(true)}
                        className={`input ${errors.customerid ? 'border-red-500' : ''}`}
                      />
                      {dropdownOpen && (
                        <div className="absolute z-10 w-[60%] mt-11 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto">
                          {filteredCustomer.length > 0 ? (
                            filteredCustomer.map((item) => (
                              <div
                                key={item.id}
                                className="px-4 py-2 hover:bg-gray-100 cursor-pointer"
                                onClick={() => handleCustomerSelect(item)}
                              >
                                {item.fullname}
                              </div>
                            ))
                          ) : (
                            <div className="px-4 py-2 text-gray-500">
                              {isLoadingCustomer ? 'Loading...' : 'No results found'}
                            </div>
                          )}
                        </div>
                      )}
                      {errors.customerid && (
                        <span className="text-red-500 text-xs mt-1">{errors.customerid}</span>
                      )}
                    </div>
                  </div>

                  {/* Email */}
                  <div className="flex gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">Email</label>
                    <div className="grow flex flex-col">
                      <Input
                        className={`input ${errors.email ? 'border-red-500' : ''}`}
                        type="email"
                        autoComplete="off"
                        value={formField.email}
                        onChange={({ target }) => {
                          setFormField((prev) => ({ ...prev, email: target.value }));
                          setErrors((prev) => ({ ...prev, email: '' }));
                        }}
                      />
                      {errors.email && (
                        <span className="text-red-500 text-xs mt-1">{errors.email}</span>
                      )}
                    </div>
                  </div>

                  {/* Role */}
                  <div className="flex gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">Role</label>
                    <div className="grow flex flex-col">
                      <Select
                        value={formField.id_role}
                        onValueChange={(id_role) => {
                          setTimeout(() => {
                            setFormField((prev) => ({ ...prev, id_role }));
                            setErrors((prev) => ({ ...prev, id_role: '' }));
                          }, 0);
                        }}
                      >
                        <SelectTrigger className={errors.id_role ? 'border-red-500' : ''}>
                          <SelectValue placeholder="Select" />
                        </SelectTrigger>
                        <SelectContent>
                          {roles.map((role) => (
                            <SelectItem value={role.id} key={role.id}>
                              {role.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      {errors.id_role && (
                        <span className="text-red-500 text-xs mt-1">{errors.id_role}</span>
                      )}
                    </div>
                  </div>

                  {/* Status */}
                  <div className="flex gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">Status</label>
                    <div className="grow flex flex-col">
                      <Select
                        value={formField.status}
                        onValueChange={(status) => {
                          setTimeout(() => {
                            setFormField((prev) => ({ ...prev, status }));
                            setErrors((prev) => ({ ...prev, status: '' }));
                          }, 0);
                        }}
                      >
                        <SelectTrigger className={errors.status ? 'border-red-500' : ''}>
                          <SelectValue placeholder="Select" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="Y">Active</SelectItem>
                          <SelectItem value="N">Non Active</SelectItem>
                        </SelectContent>
                      </Select>
                      {errors.status && (
                        <span className="text-red-500 text-xs mt-1">{errors.status}</span>
                      )}
                    </div>
                  </div>

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

export { EditDialog };
