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 { useManagePointiersContext } from '../hooks/useManagePointiersContext';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { RefreshCw } from 'lucide-react';
import { initialStatePointiers, validateFormPointiers } from './Types';
import { Textarea } from '@/components/ui/textarea';

const API_URL = apiConfig.service_master_data;

const EditDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showEditDialog, handleEditDialog, selectedPointiers } = useManagePointiersContext();
  const { reload } = useDataGrid();
  const { PutData, GetData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const [isLoading, setIsLoading] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

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

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

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

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

      try {
        const payload = {
          name: formField.name,
          description: formField.description,
          minimal_point: formField.minimal_point,
          status: formField.status,
          updated_by: parsedUser.username,
          updated_at: formattedTime
        };

        const response = await PutData(`${API_URL}/pointiers/update/${selectedPointiers}`, payload);

        if (response?.status) {
          resetForm();
          handleEditDialog(false, null);
          toast.success('Success Update Pointiers');
          reload();
          const editActivity = {
            module: 'Manage Pointiers',
            description: `Edit Pointiers => ${formField.name}`,
            action: 'U'
          };

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

  const handleRestore = useCallback(async () => {
    setIsSubmitting(true);

    try {
      const response = await PutData(`${API_URL}/pointiers/restore/${selectedPointiers}`, {
        updated_by: parsedUser.username,
        updated_at: formattedTime
      });

      if (response?.status) {
        toast.success('Success Restore Pointiers');
        handleEditDialog(false, null);
        reload();
      } else {
        toast.error(response?.message);
      }
    } catch (error) {
      toast.error('Failed to restore pointiers');
    } finally {
      setIsSubmitting(false);
    }
  }, [selectedPointiers, parsedUser.username, formattedTime]);

  const doFetchData = useCallback(async (id: string) => {
    setIsLoading(true);
    const minDelay = new Promise((resolve) => setTimeout(resolve, 300));
    const fetchData = GetData(`${API_URL}/pointiers/getdata/${id}`, { id });
    const [response] = await Promise.all([fetchData, minDelay]);

    if (response?.status) {
      setFormField((prev) => ({
        ...prev,
        name: response.data.name,
        description: response.data.description,
        minimal_point: response.data.minimal_point,
        status: response.data.status
      }));
    }
    setIsLoading(false);
  }, []);

  useEffect(() => {
    if (selectedPointiers) {
      doFetchData(selectedPointiers);
    }
  }, [selectedPointiers]);

  useEffect(() => {
    if (showEditDialog && selectedPointiers) {
      setFormField((prev) => ({
        ...prev,
        updated_by: parsedUser.username,
        updated_at: formattedTime
      }));
    }
  }, [showEditDialog, selectedPointiers]);

  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>Pointiers - Update</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody ref={parentRef}>
          <div className="flex flex-col">
            {isLoading ? (
              <div className="flex flex-col items-center justify-center p-8">
                <div className="animate-pulse flex space-x-4 w-full">
                  <div className="flex-1 space-y-4 py-1">
                    <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                    <div className="space-y-2">
                      <div className="h-4 bg-gray-200 rounded"></div>
                      <div className="h-4 bg-gray-200 rounded w-5/6"></div>
                    </div>
                  </div>
                </div>
                <p className="mt-4 text-gray-500">Loading Pointiers Details...</p>
              </div>
            ) : (
              <form onSubmit={doUpdatePointiers}>
                <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"
                      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>

                  {/* Pointiers Type */}
                  <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.description ? 'border-red-500' : ''}`}
                      autoComplete="off"
                      value={formField.description}
                      onChange={({ target }) => {
                        setFormField((prev) => ({ ...prev, description: target.value }));
                        setErrors((prev) => ({ ...prev, description: '' }));
                      }}
                    />
                    {errors.type && (
                      <span className="text-red-500 text-xs mt-1 col-span-8 ml-[calc(25%+0.5rem)]">
                        {errors.type}
                      </span>
                    )}
                  </div>

                  {/* minimal point */}
                  <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> */}
                    <div className="flex justify-end gap-5">
                      <Button
                        type="button"
                        variant="outline"
                        onClick={handleRestore}
                        disabled={isSubmitting}
                      >
                        {isSubmitting ? (
                          <RefreshCw className="animate-spin h-8 w-8 text-white mx-3" />
                        ) : (
                          'Restore'
                        )}
                      </Button>
                      <Button variant="default" type="submit" disabled={isSubmitting}>
                        {isSubmitting ? (
                          <RefreshCw className="animate-spin h-8 w-8 text-white mx-3" />
                        ) : (
                          'Update'
                        )}
                      </Button>
                    </div>
                  </div>
                </div>
              </form>
            )}
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;
