import { Alert, useDataGrid } from '@/components';
import { useManageMenusContext } from '../hooks/useManageMenusContext';
import { useCallApi } from '@/hooks';
import { apiConfig } from '@/config/api.config';
import React, { useCallback, useState, useEffect } from 'react';
import { toast } from 'sonner';
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { FormControl, NativeSelect } from '@mui/material';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { doSaveLogActivity } from '@/actions/GlobalActions';

const API_URL = apiConfig.service_dashboard;

const EditDialog = () => {
  const { showEditDialog, handleEditDialog, selectedMenu, setSelectedMenu, parents }: any =
    useManageMenusContext();
  const { reload } = useDataGrid();
  const { PutData } = useCallApi();
  const [open, setOpen] = useState(false);
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const initialState = {
    id: '',
    module: '',
    name: '',
    link: '',
    id_parent: '',
    order_number: 0,
    icon: '',
    status: ''
  };

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

    if (
      selectedMenu.module === '' ||
      selectedMenu.name === '' ||
      selectedMenu.link === '' ||
      selectedMenu.id_parent === '' ||
      selectedMenu.order_number === 0 ||
      selectedMenu.status === ''
    ) {
      setAlert({ show: true, message: 'Please fill in all required fields.' });
      return;
    }

    const updateMenu = selectedMenu;
    if (updateMenu.id_parent === null) updateMenu.id_parent = '';
    delete updateMenu.parentName;
    const response = await PutData(`${API_URL}/menus/update/${selectedMenu.id}`, selectedMenu);
    if (response?.status) {
      handleEditDialog(false, null);
      resetForm();
      toast.success('Success Update Menu');
      const createActivity = {
        module: 'Manage Menu',
        description: `Update Menu => ${selectedMenu.name}`,
        action: 'U'
      };

      doSaveLogActivity(createActivity);
      reload();
    } else {
      toast.error('Failed Update Menu');
      setAlert({ show: true, message: 'Failed Update Menu' });
    }
    setAlert({ show: false, message: '' });
  };

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

  return (
    <Dialog open={showEditDialog} onOpenChange={(open) => handleEditDialog(open, null)}>
      <DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
        <DialogHeader>
          <DialogTitle>Menu - Update</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody className="scrollable">
          <div className="flex flex-col">
            {alert.show && (
              <Alert variant="danger">
                <h3>{alert.message}</h3>
              </Alert>
            )}

            <form onSubmit={handleUpdate}>
              <div className="card-body grid gap-5">
                <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">
                      Module<span className="text-red-500">*</span>
                    </label>
                    <Input
                      className="input"
                      type="text"
                      value={selectedMenu.module}
                      onChange={(e) => setSelectedMenu({ ...selectedMenu, module: e.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">
                      Name<span className="text-red-500">*</span>
                    </label>
                    <Input
                      className="input"
                      type="text"
                      value={selectedMenu.name}
                      onChange={(e) => setSelectedMenu({ ...selectedMenu, name: e.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">
                      Link<span className="text-red-500">*</span>
                    </label>
                    <Input
                      className="input"
                      type="text"
                      value={selectedMenu.link}
                      onChange={(e) => setSelectedMenu({ ...selectedMenu, link: e.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">Parent</label>
                    <Select
                      value={selectedMenu.id_parent || ''}
                      onValueChange={(value) => {
                        setSelectedMenu({
                          ...selectedMenu,
                          id_parent: value === '' ? null : value
                        });
                      }}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select As Parent" />
                      </SelectTrigger>
                      <SelectContent>
                        {parents.map((parent: any) => (
                          <SelectItem key={parent.id} value={parent.id}>
                            {parent.name}
                          </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">
                      Order Number<span className="text-red-500">*</span>
                    </label>
                    <Input
                      className="input"
                      type="number"
                      min={0}
                      value={selectedMenu.order_number === 0 ? '' : selectedMenu.order_number}
                      onChange={(e) => {
                        const value = parseInt(e.target.value, 10);
                        setSelectedMenu({
                          ...selectedMenu,
                          order_number: isNaN(value) ? 0 : 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">Icon</label>
                    <Input
                      className="input"
                      type="text"
                      value={selectedMenu.icon}
                      onChange={(e) => setSelectedMenu({ ...selectedMenu, icon: e.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">
                      Status<span className="text-red-500">*</span>
                    </label>
                    <Select
                      value={selectedMenu.status}
                      onValueChange={(value) => setSelectedMenu({ ...selectedMenu, status: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Status" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Y">Active</SelectItem>
                        <SelectItem value="N">Inactive</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">
                      Status<span className="text-red-500">*</span>
                    </label>
                    <FormControl fullWidth margin="dense">
                      <NativeSelect
                        defaultValue={30}
                        value={selectedMenu.status}
                        onChange={(e) => setSelectedMenu({ ...selectedMenu, status: e.target.value })}
                        inputProps={{
                          name: 'status',
                          id: 'uncontrolled-native',
                        }}
                      >
                        <option value={"Y"}>Active</option>
                        <option value={"N"}>Inactive</option>
                      </NativeSelect>
                    </FormControl>
                  </div>
                </div> */}

                <div className="flex justify-end">
                  <Button className="btn btn-primary">Save Changes</Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;
