import { apiConfig } from '@/config/api.config';
import React, { useCallback, useRef, useState } from 'react';
import { useManageMenusContext } from '../hooks/useManageMenusContext';
import { Alert, useDataGrid } from '@/components';
import { useCallApi } from '@/hooks';
import { toast } from 'sonner';
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
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';
import { RefreshCw } from 'lucide-react';

const API_URL = apiConfig.service_dashboard;
const AddDialog = () => {
  const { showAddDialog, handleAddDialog, parents, selectedMenu } = useManageMenusContext();
  const { reload } = useDataGrid();
  const { PostData } = useCallApi();
  const [open, setOpen] = useState(false);
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const initialState = {
    module: '',
    name: '',
    link: '',
    id_parent: '',
    order_number: 0,
    icon: '',
    status: ''
  };
  const [formField, setFormField] = useState(initialState);
  const [isSubmitting, setIsSubmitting] = useState(false);

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

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

    try {
      const response = await PostData(`${API_URL}/menus/create`, formField);

      if (response?.status) {
        handleAddDialog(false);
        resetForm();
        toast.success('Success Create Menu');
        const createActivity = {
          module: 'Manage Menu',
          description: `Create Menu => ${selectedMenu}`,
          action: 'C'
        };

        doSaveLogActivity(createActivity);
        reload();
      } else {
        toast.error('Failed Create Menu');
        setAlert({ show: true, message: response?.message });
      }
    } catch (error) {
      toast.error('Something went wrong, please try again');
    } finally {
      setIsSubmitting(false);
    }

    setAlert({ show: false, message: '' });
  };

  const handleAddDialogChange = (open: boolean) => {
    handleAddDialog(open);

    if(!open) {
      resetForm();
    }
  }

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

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

            <form onSubmit={handleSubmit}>
              <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={formField.module}
                      onChange={(e) => setFormField({ ...formField, 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={formField.name}
                      onChange={(e) => setFormField({ ...formField, 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={formField.link}
                      onChange={(e) => setFormField({ ...formField, 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={formField.id_parent}
                      onValueChange={(value) => setFormField({ ...formField, id_parent: 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={formField.order_number === 0 ? '' : formField.order_number}
                      onChange={(e) => {
                        const value = parseInt(e.target.value, 10);
                        setFormField({ ...formField, 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
                      disabled
                      className="input"
                      type="text"
                      value={formField.icon}
                      onChange={(e) => setFormField({ ...formField, 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">
                      Status<span className="text-red-500">*</span>
                    </label>
                    <Select
                      value={formField.status}
                      onValueChange={(value) => setFormField({ ...formField, 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="flex justify-end gap-5">
                  <Button type="button" variant="outline" onClick={resetForm}>
                    Reset
                  </Button>
                  <Button variant="default" type="submit" disabled={isSubmitting}>
                    {isSubmitting ? (
                      <RefreshCw className="animate-spin h-8 w-8 text-white mx-3" />
                    ) : (
                      'Create'
                    )}
                  </Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default AddDialog;
