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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { useManageCurrencyContext } from '../hooks/useManageCurrencyContext';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { RefreshCw } from 'lucide-react';
import { initialStateCurrency, validateFormCurrency } 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, selectedCurrency } = useManageCurrencyContext();
  const { reload } = useDataGrid();
  const { PostData, GetData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const [currencies, setCurrencies] = useState<CurrencyProps[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [formField, setFormField] = useState(initialStateCurrency);
  const created_time = new Date();
  const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');

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

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

      try {
        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(response?.message);
        }
      } catch (error) {
        toast.error('Something went wrong');
      } finally {
        setIsSubmitting(false);
      }
    },
    [formField]
  );

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

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

    doCreateCurrency(e);
  };

  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>Currency - 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="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 ${errors.code ? 'border-red-500' : ''}`}
                    type="text"
                    autoComplete="off"
                    value={formField.code}
                    onChange={({ target }) => {
                      setFormField((prev) => ({ ...prev, code: target.value }));
                      setErrors((prev) => ({ ...prev, code: '' }));
                    }}
                  />
                  {errors.code && (
                    <span className="text-red-500 text-xs mt-1 col-span-8 ml-[calc(25%+0.5rem)]">
                      {errors.code}
                    </span>
                  )}
                </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 ${errors.name ? 'border-red-500' : ''}`}
                    type="text"
                    autoComplete="off"
                    value={formField.name}
                    onChange={({ target }) => {
                      setFormField((prev) => ({ ...prev, name: target.value }));
                      setErrors((prev) => ({ ...prev, name: '' }));
                    }}
                  />
                  {errors.name && (
                    <span className="text-red-500 text-xs mt-1 col-span-8 ml-[calc(25%+0.5rem)]">
                      {errors.name}
                    </span>
                  )}
                </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 ${errors.prefix ? 'border-red-500' : ''}`}
                    type="text"
                    autoComplete="off"
                    value={formField.prefix}
                    onChange={({ target }) => {
                      setFormField((prev) => ({ ...prev, prefix: target.value }));
                      setErrors((prev) => ({ ...prev, prefix: '' }));
                    }}
                  />
                  {errors.prefix && (
                    <span className="text-red-500 text-xs mt-1 col-span-8 ml-[calc(25%+0.5rem)]">
                      {errors.prefix}
                    </span>
                  )}
                </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 }));
                        setErrors((prev) => ({ ...prev, status: '' }));
                      }}
                    >
                      <SelectTrigger className={`w-full ${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 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;
