import { apiConfig } from '@/config/api.config';
import { Alert, useDataGrid } from '@/components';
import { useCallApi } from '@/hooks';
import { getAuth } from '@/auth';
import React, { useCallback, useEffect, useRef, useState } from 'react';
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 { NumericFormat } from 'react-number-format';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from '@/components/ui/command';
import { set } from 'date-fns';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { useManageCurrencyContext } from '../hooks/useManageCurrencyContext';
import { prefix } from 'stylis';
import { doSaveLogActivity } from '@/actions/GlobalActions';
interface CurrencyProps {
  ID: string;
  name: string;
}

const API_URL = apiConfig.service_wallet;

const AddDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showAddDialog, handleAddDialog, selectedCurrency } = useManageCurrencyContext();
  const { reload } = useDataGrid();
  const { PostData, GetData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const [currencies, setCurrencies] = useState<CurrencyProps[]>([]);
  const [open, setOpen] = useState(false);
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const initialState = {
    code: '',
    name: '',
    prefix: '',
    status: '',
    created_by: '',
    created_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 doCreateCurrency = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();

      const response = await PostData(`${API_URL}/dashboard/currency/`, formField);

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

        doSaveLogActivity(createActivity);
        reload();
      } else {
        toast.error('Error Create Currency');
        setAlert({ show: true, message: 'Failed to create Currency. Please try again.' });
      }
    },
    [formField]
  );

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

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

    doCreateCurrency(e);
    // console.log(formField);
    setAlert({ show: false, message: '' });
  };

  useEffect(() => {
    if (showAddDialog) {
      setFormField({
        ...formField,
        created_by: parsedUser.username,
        created_at: formattedTime
      });
    }
  }, [formattedTime]);

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

  return (
    <Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}>
      <DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
        <DialogHeader>
          <DialogTitle>Cuurency - Create</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody ref={parentRef}>
          <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="grid grid-cols-8 gap-2 w-full items-center">
                  <label className="form-label flex items-center gap-1 col-span-2">
                    Code<span className="text-red-500">*</span>
                  </label>

                  <Input
                    className="input col-span-6"
                    type="text"
                    autoComplete="off"
                    value={formField.code}
                    onChange={({ target }) =>
                      setFormField((prev) => ({ ...prev, code: target.value }))
                    }
                  />
                </div>
                <div className="grid grid-cols-8 gap-2 w-full items-center">
                  <label className="form-label flex items-center gap-1 col-span-2">
                    Name<span className="text-red-500">*</span>
                  </label>

                  <Input
                    className="input col-span-6"
                    type="text"
                    autoComplete="off"
                    value={formField.name}
                    onChange={({ target }) =>
                      setFormField((prev) => ({ ...prev, name: target.value }))
                    }
                  />
                </div>
                <div className="grid grid-cols-8 gap-2 w-full items-center">
                  <label className="form-label flex items-center gap-1 col-span-2">
                    Prefix<span className="text-red-500">*</span>
                  </label>

                  <Input
                    className="input col-span-6"
                    type="text"
                    autoComplete="off"
                    value={formField.prefix}
                    onChange={({ target }) =>
                      setFormField((prev) => ({ ...prev, prefix: target.value }))
                    }
                  />
                </div>

                <div className="grid grid-cols-8 gap-2 w-full items-center">
                  <label className="form-label flex items-center gap-1 col-span-2">
                    Status<span className="text-red-500">*</span>
                  </label>

                  <div className="col-span-6">
                    <Select
                      value={formField.status}
                      onValueChange={(value) =>
                        setFormField((prev) => ({ ...prev, status: value }))
                      }
                    >
                      <SelectTrigger className="w-full">
                        <SelectValue placeholder="Select" />
                      </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">Save Changes</Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default AddDialog;
