import { 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';

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

const API_URL = apiConfig.service_dashboard;

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

const EditDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showEditDialog, selectedUser, handleEditDialog } = useUserContext();
  const { reload } = useDataGrid();
  const { GetData, PutData } = useCallApi();
  const [roles, setRoles] = useState<RoleListProps[]>([]);
  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 doFetchUserData = useCallback(async (id: string) => {
    const response = await GetData(`${API_URL}/user/detail/${id}`, { id });
    // console.log('User detail response:', response);

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

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

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

  useEffect(() => {
    const fetchAllData = async () => {
      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">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 };
