import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { Alert, KeenIcon, useDataGrid } from '@/components';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { apiConfig } from '@/config/api.config';
import { toast } from 'sonner';
import { getAuth } from '@/auth';
import { useCallApi } from '@/hooks';
import { NumericFormat } from 'react-number-format';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { RefreshCw } from 'lucide-react';
import { initialStatePointiers, validateFormPointiers } from '../../pointiers/blocks/Types';
import { Textarea } from '@/components/ui/textarea';
import { useManagePointiersContext } from '../hooks/useManagePointiersContext';

const API_URL = apiConfig.service_master_data;

const AddDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showAddDialog, handleAddDialog } = useManagePointiersContext();
  const { reload } = useDataGrid();
  const { PostData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const [errors, setErrors] = useState<Record<string, string>>({});

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

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

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setFormField({ ...formField, [e.target.name]: e.target.value });
  };

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

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

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

          doSaveLogActivity(createActivity);
        } else {
          toast.error(response?.message);
        }
      } catch (error) {
        toast.error('Something went wrong, please try again.');
      } finally {
        setIsSubmitting(false);
      }
    },
    [formField]
  );

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

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

    doCreatePointiers(e);
  };

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

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

  return (
    <Dialog open={showAddDialog} onOpenChange={handleAddDialog}>
      <DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
        <DialogHeader>
          <DialogTitle>Pointiers - Create</DialogTitle>
          <DialogDescription />
        </DialogHeader>
        <DialogBody ref={parentRef}>
          <div className="flex flex-col">
            <form onSubmit={handleSubmit}>
              <div className="card-body grid gap-5">
                {/* Pointiers Name */}
                <div className="grid grid-cols-8 gap-2 items-center">
                  <label className="form-label flex items-center gap-1 col-span-2">
                    Pointiers Name<span className="text-red-500">*</span>
                  </label>
                  <Input
                    className={`input col-span-6 ${errors.name ? 'border-red-500' : ''}`}
                    type="text"
                    placeholder="Enter Name"
                    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>

                {/* Description */}
                <div className="grid grid-cols-8 gap-2 items-center">
                  <label className="form-label flex items-center gap-1 col-span-2">
                    Description <span className="text-red-500">*</span>
                  </label>
                  <Textarea
                    className={`input col-span-6 ${errors.name ? 'border-red-500' : ''}`}
                    name="description"
                    placeholder="Enter Description"
                    value={formField.description}
                    onChange={handleChange}
                  />
                  {errors.description && (
                    <span className="text-red-500 text-xs mt-1 col-span-8 ml-[calc(25%+0.5rem)]">
                      {errors.description}
                    </span>
                  )}
                </div>

                {/* Amount */}
                <div className="grid grid-cols-8 gap-2 items-center">
                  <label className="form-label flex items-center gap-1 col-span-2">
                    Minimal Point<span className="text-red-500">*</span>
                  </label>
                  <NumericFormat
                    className={`input col-span-6 ${errors.minimal_point ? 'border-red-500' : ''}`}
                    value={formField.minimal_point}
                    thousandSeparator="."
                    decimalSeparator=","
                    allowNegative={false}
                    onValueChange={(values) => {
                      setFormField((prev) => ({
                        ...prev,
                        minimal_point: values.floatValue ?? null
                      }));
                      setErrors((prev) => ({ ...prev, minimal_point: '' }));
                    }}
                    placeholder="Enter Point"
                  />
                  {errors.minimal_point && (
                    <span className="text-red-500 text-xs mt-1 col-span-8 ml-[calc(25%+0.5rem)]">
                      {errors.minimal_point}
                    </span>
                  )}
                </div>

                {/* Status */}
                <div className="grid grid-cols-8 gap-2 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>
                  </div>
                  {errors.status && (
                    <span className="text-red-500 text-xs mt-1 col-span-8 ml-[calc(25%+0.5rem)]">
                      {errors.status}
                    </span>
                  )}
                </div>

                {/* Actions */}
                <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;
