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 { doSaveLogActivity } from '@/actions/GlobalActions';
interface CurrencyProps {
  ID: string;
  name: string;
}

const API_URL = apiConfig.service_wallet;

const EditDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showEditDialog, handleEditDialog, selectedCurrency } = useManageCurrencyContext();
  const { reload } = useDataGrid();
  const { PostData, GetData, PutData } = 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 updated_time = new Date();
  const formattedTime = updated_time.toISOString().slice(0, 19).replace('T', ' ');

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

  const doUpdateCurrency = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      if (!showEditDialog) return;
      const response = await PutData(`${API_URL}/dashboard/currency/${selectedCurrency}`, {
        ...formField
      });

      if (response?.status) {
        resetForm();
        handleEditDialog(false, null);
        toast.success('Success Update Currency');
        const createActivity = {
          module: 'Manage Currency',
          description: `Update Currency=> ${selectedCurrency}`,
          action: 'U'
        };

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

  const doGetCurrencyById = useCallback(async (id: string) => {
    const response = await GetData(`${API_URL}/dashboard/currency/${id}`, { id });
    // console.log('Transaction Type: ', response?.data);
    if (response?.status) {
      setFormField((prev) => ({
        ...prev,
        status: response.data.status,
        code: response.data.code,
        name: response.data.name,
        prefix: response.data.prefix
      }));
    }
    // console.log('form fieldd Transaction Type: ', formField);
  }, []);

  useEffect(() => {
    if (selectedCurrency) {
      doGetCurrencyById(selectedCurrency);
    }
  }, [selectedCurrency]);

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

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

  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>Currency - Update</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody ref={parentRef}>
          <div className="flex flex-col">
            {alert.show && (
              <Alert variant="danger">
                <h3>{alert.message}</h3>
              </Alert>
            )}

            <form onSubmit={doUpdateCurrency}>
              <div className="card-body grid gap-5">
                <div className="w-full">
                  <label className="form-label">
                    Code
                    <span className="text-red-500">*</span>
                  </label>
                  <Input
                    type="text"
                    placeholder="Code"
                    value={formField.code}
                    onChange={(e) => setFormField((prev) => ({ ...prev, code: e.target.value }))}
                  />
                </div>
                <div className="w-full">
                  <label className="form-label">
                    Name
                    <span className="text-red-500">*</span>
                  </label>
                  <Input
                    type="text"
                    placeholder="Code"
                    value={formField.name}
                    onChange={(e) => setFormField((prev) => ({ ...prev, name: e.target.value }))}
                  />
                </div>

                <div className="w-full">
                  <label className="form-label">
                    Prefix
                    <span className="text-red-500">*</span>
                  </label>
                  <Input
                    type="text"
                    placeholder="Code"
                    value={formField.prefix}
                    onChange={(e) => setFormField((prev) => ({ ...prev, prefix: e.target.value }))}
                  />
                </div>

                <div className="w-full">
                  <label className="form-label">
                    Status
                    <span className="text-red-500">*</span>
                  </label>

                  <Select
                    value={formField.status}
                    onValueChange={(value) => setFormField((prev) => ({ ...prev, status: value }))}
                  >
                    <SelectTrigger className="w-full">
                      <SelectValue placeholder="Select" defaultValue={formField.status} />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="Y">Active</SelectItem>
                      <SelectItem value="N">Inactive</SelectItem>
                    </SelectContent>
                  </Select>
                </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 EditDialog;
