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 { CustomerProps } from './AddDialog';
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';

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

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

const initialState = {
  name: '',
  username: '',
  email: '',
  id_role: '',
  status: '',
  customerid: ''
};

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 [alert, setAlert] = useState({
    show: false,
    message: ''
  });

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

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

  /* actions */
  const doUpdateUser = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      const response = await PutData(`${API_URL}/user/update/${selectedUser}`, {
        ...formField
      });

      if (formField.name.trim() === '') {
        setAlert({ show: true, message: 'Please fill all required field' });
        return;
      }

      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 {
        setAlert((prev) => ({ ...prev, show: true, message: response?.message }));
      }
    },
    [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'
      });

      // console.log('User ID_ROLE:', response?.data.id_role);
      // console.log('Role: ', response?.data.list);
      setRoles(response?.data.list);
    } catch (error) {
      console.error('Error fetching role', error);
    }
  }, []);

  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'
      });

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

  const doFetchUserData = useCallback(async (id: string) => {
    const response = await GetData(`${API_URL}/user/detail/${id}`, { id });
    // console.log('User detail response:', response?.data);

    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 || ''
      }));
      // console.log('Customer ID from API:', response?.data.customerid);
    } else {
      setFormField((prev) => ({
        ...prev,
        name: '',
        username: '',
        email: '',
        id_role: '0',
        status: '',
        customerid: ''
      }));
    }
    // console.log('Fetched ID Role:', response?.data.id_role);
  }, []);

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

  useEffect(() => {
    const fetchAllData = async () => {
      await getCustomerList([{ id: 'id', desc: false }]);
      await doFetchUserRole([{ id: 'name', desc: false }]);
      if (selectedUser) {
        await doFetchUserData(selectedUser);
      }
    };

    fetchAllData();
  }, [selectedUser]);

  // console.log('ini role: ', roles);
  // useEffect(() => {
  //   console.log('Selected User ID Role:', formField.id_role);
  //   // console.log('Available Roles:', roles);
  // }, [formField.id_role, roles]);

  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">
            {alert.show && (
              <Alert variant="danger">
                <h3>{alert.message}</h3>
              </Alert>
            )}
            <form onSubmit={doUpdateUser}>
              <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"
                      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"
                      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"
                      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) => {
                          // console.log('Role changed to:', id_role);
                          setFormField((prev) => ({ ...prev, id_role }));
                        }}
                      >
                        <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="flex justify-end">
                  <Button className="btn btn-primary">Save Changes</Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export { EditDialog };
