import { Alert, useDataGrid } from '@/components';
import { useManageSucosContext } from '../hooks/useManageSucosContext';
import { useCallApi } from '@/hooks';
import { getAuth } from '@/auth';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { apiConfig } from '@/config/api.config';
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 { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from '@/components/ui/command';

interface PostoAdmsProps {
  PostoAdms_id: number; // Ubah ke PostoAdms_id
  PostoAdms_name: string; // Ubah ke PostoAdms_name
}

const API_URL = apiConfig.service_master_data;

const EditDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showEditDialog, handleEditDialog, selectedSucos, sucos } = useManageSucosContext();
  const { reload } = useDataGrid();
  const { PutData, GetData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const [open, setOpen] = useState(false);
  const [postoadms, setPostoadms] = useState<PostoAdmsProps[]>([]);

  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });

  const initialState = {
    name: '',
    posto_adm_id: 0, // Pastikan ini sesuai dengan PostoAdms_id
    updated_by: '',
    updated_at: ''
  };

  const [formField, setFormField] = useState(initialState);
  const created_time = new Date();
  const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');

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

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

      const response = await PutData(`${API_URL}/sucos/update/${selectedSucos}`, formField);

      if (response?.status) {
        resetForm();
        handleEditDialog(false, null);
        toast.success('Success Update Sucos');
        reload();
      } else {
        toast.error('Failed Update Sucos');
        setAlert({ show: true, message: 'Failed Update Sucos. Please try again' });
      }
    },
    [selectedSucos, formField]
  );

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

      setPostoadms(response?.data.list);
      console.log('Data Posto Adms:', response?.data.list); // Log data postoadms
    } catch (error) {
      console.log('Error fetching postoadms', error);
    }
  }, []);

  const doFetchData = useCallback(async (id: string) => {
    const response = await GetData(`${API_URL}/sucos/getdata/${id}`, { id });
    console.log('Data Sucos:', response?.data); // Log data sucos

    if (response?.status) {
      setFormField((prev) => ({
        ...prev,
        name: response.data.name,
        posto_adm_id: response.data.posto.id // Pastikan ini sesuai dengan PostoAdms_id
      }));
    } else {
      setFormField((prev) => ({
        ...prev,
        name: ''
      }));
    }
  }, []);

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

    if (formField.name.trim() === '' || formField.posto_adm_id === 0) {
      setAlert({ show: true, message: 'Please fill in all required fields.' });
      return;
    }

    console.log('Form Field before update:', formField); // Log formField sebelum update
    doUpdateSucos(e);
    setAlert({ show: false, message: '' });
  };

  useEffect(() => {
    if (showEditDialog) {
      resetForm();
      console.log('Edit Dialog Opened'); // Log ketika dialog dibuka
    }
  }, [showEditDialog]);

  useEffect(() => {
    if (selectedSucos) {
      doFetchData(selectedSucos);
      console.log('Selected Sucos ID:', selectedSucos); // Log selectedSucos ID
    }
  }, [selectedSucos]);

  useEffect(() => {
    if (selectedSucos) {
      setFormField({
        ...formField,
        updated_by: parsedUser?.username,
        updated_at: formattedTime
      });
      console.log('Form Field after update:', formField); // Log formField setelah update
    }
  }, [formattedTime]);

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

  console.log(selectedSucos);
  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>Sucos - Update</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody>
          <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">
                      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">
                      Posto Administrativo Name
                      <span className="text-red-500">*</span>
                    </label>
                    <Popover open={open} onOpenChange={setOpen}>
                      <PopoverTrigger asChild>
                        <button type="button" className="input col-span-5 text-left">
                          {postoadms.find((posto) => posto.PostoAdms_id === formField.posto_adm_id)
                            ?.PostoAdms_name || 'Select Posto Adms'}
                        </button>
                      </PopoverTrigger>
                      <PopoverContent className="w-[400px] p-0">
                        <Command>
                          <CommandInput placeholder="Search Posto Adms..." />
                          <CommandList>
                            <CommandEmpty>No Posto Adms Found.</CommandEmpty>
                            <CommandGroup>
                              {postoadms.map((posto) => (
                                <CommandItem
                                  key={posto.PostoAdms_id}
                                  value={posto.PostoAdms_name}
                                  onSelect={() => {
                                    setFormField({
                                      ...formField,
                                      posto_adm_id: posto.PostoAdms_id // Gunakan PostoAdms_id
                                    });
                                    setOpen(false);
                                  }}
                                >
                                  {posto.PostoAdms_name}
                                </CommandItem>
                              ))}
                            </CommandGroup>
                          </CommandList>
                        </Command>
                      </PopoverContent>
                    </Popover>
                  </div>
                </div>

                <div className="flex justify-end gap-5">
                  <Button type="button" variant="outline" onClick={resetForm}>
                    Reset
                  </Button>
                  <Button className="btn btn-primary">Save Changes</Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;
