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 { useManageConversionContext } from '../hooks/useManageConversionContext';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { RefreshCw } from 'lucide-react';
import { initialStateConversion, validateFormConversion } from './Types';
interface CurrencyProps {
  ID: string;
  name: string;
}

const API_URL = apiConfig.service_wallet;

const AddDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showAddDialog, handleAddDialog, selectedConversion } = useManageConversionContext();
  const { reload } = useDataGrid();
  const { PostData, GetData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const [currencies, setCurrencies] = useState<CurrencyProps[]>([]);
  const [open, setOpen] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [formField, setFormField] = useState(initialStateConversion);
  const created_time = new Date();
  const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const resetForm = () => {
    setFormField(initialStateConversion);
    setErrors({});
  };

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

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

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

          doSaveLogActivity(createActivity);
          reload();
        } else {
          toast.error(response?.message);
        }
      } catch (error) {
        toast.error('Something Went Wrong');
      } finally {
        setIsSubmitting(false);
      }
    },
    [formField]
  );

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

      setCurrencies(response?.data.list);
    } catch (error) {
      console.error('Error fetching currency', error);
    }
  };

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

    if (!validateFormConversion(formField, setErrors)) {
      return;
    }

    doCreateConversion(e);
  };

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

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

  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>Conversion - Create</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody ref={parentRef}>
          <div className="flex flex-col">
            <form onSubmit={handleSubmit}>
              <div className="card-body grid gap-5">
                <div className="w-full">
                  <label className="form-label">
                    Currency Origin <span className="text-red-500">*</span>
                  </label>
                  <Select
                    value={formField.id_currency_origin}
                    onValueChange={(id_currency_origin) => {
                      setFormField((prev) => ({ ...prev, id_currency_origin }));
                      setErrors((prev) => ({ ...prev, id_currency_destination: '' }));
                    }}
                  >
                    <SelectTrigger
                      className={errors.id_currency_destination ? 'border-red-500' : ''}
                    >
                      <SelectValue placeholder="Select Currency" />
                    </SelectTrigger>
                    <SelectContent>
                      {currencies.map((currency, idx) => (
                        <SelectItem value={currency.ID} key={currency.ID}>
                          {currency.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  {errors.id_currency_destination && (
                    <span className="text-red-500 text-xs mt-1">
                      {errors.id_currency_destination}
                    </span>
                  )}
                </div>
                <div className="w-full">
                  <label className="form-label">
                    Currency Destination <span className="text-red-500">*</span>
                  </label>
                  <Select
                    value={formField.id_currency_destination}
                    onValueChange={(id_currency_destination) => {
                      setFormField((prev) => ({ ...prev, id_currency_destination }));
                      setErrors((prev) => ({ ...prev, id_currency_origin: '' }));
                    }}
                  >
                    <SelectTrigger className={errors.id_currency_origin ? 'border-red-500' : ''}>
                      <SelectValue placeholder="Select Currency" />
                    </SelectTrigger>
                    <SelectContent>
                      {currencies.map((currency, idx) => (
                        <SelectItem value={currency.ID} key={currency.ID}>
                          {currency.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  {errors.id_currency_origin && (
                    <span className="text-red-500 text-xs mt-1">{errors.id_currency_origin}</span>
                  )}
                </div>
                <div className="w-full">
                  <label className="form-label">
                    Buy<span className="text-red-500">*</span>
                  </label>
                  <NumericFormat
                    className={`input ${errors.buy ? 'border-red-500' : ''}`}
                    value={formField.buy}
                    thousandSeparator="."
                    decimalSeparator=","
                    allowNegative={false}
                    onValueChange={(values) => {
                      setFormField((prev) => ({
                        ...prev,
                        buy: values.floatValue ?? null
                      }));
                      setErrors((prev) => ({ ...prev, buy: '' }));
                    }}
                    placeholder="Enter Buy"
                  />
                  {errors.buy && <span className="text-red-500 text-xs mt-1">{errors.buy}</span>}
                </div>
                <div className="w-full">
                  <label className="form-label">
                    Sell
                    <span className="text-red-500">*</span>
                  </label>
                  <NumericFormat
                    className={`input ${errors.sell ? 'border-red-500' : ''}`}
                    value={formField.sell}
                    thousandSeparator="."
                    decimalSeparator=","
                    allowNegative={false}
                    onValueChange={(values) => {
                      setFormField((prev) => ({
                        ...prev,
                        sell: values.floatValue ?? null
                      }));
                      setErrors((prev) => ({ ...prev, sell: '' }));
                    }}
                    placeholder="Enter Sell"
                  />
                  {errors.sell && <span className="text-red-500 text-xs mt-1">{errors.sell}</span>}
                </div>
                <div className="w-full">
                  <label className="form-label">
                    Status
                    <span className="text-red-500">*</span>
                  </label>

                  <div className="grow">
                    <Select
                      value={formField.status}
                      onValueChange={(value) => {
                        setFormField((prev) => ({ ...prev, status: value }));
                        setErrors((prev) => ({ ...prev, status: '' }));
                      }}
                    >
                      <SelectTrigger className={errors.status ? 'border-red-500' : ''}>
                        <SelectValue placeholder="Select" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Y">Active</SelectItem>
                        <SelectItem value="N">Inactive</SelectItem>
                      </SelectContent>
                    </Select>
                    {errors.status && (
                      <span className="text-red-500 text-xs mt-1">{errors.status}</span>
                    )}
                  </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;
