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 { useManageRewardContext } from '../hooks/useManageRewardContext';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { RefreshCw } from 'lucide-react';

const API_URL = apiConfig.service_master_data;

const EditDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showEditDialog, handleEditDialog, selectedReward } = useManageRewardContext();
  const { reload } = useDataGrid();
  const { PutData, GetData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const [isLoading, setIsLoading] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });

  const initialState = {
    name: '',
    type: '',
    amount: 0,
    status: '',
    updated_by: '',
    updated_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 RewardType = {
    'Daily Check in': 'D',
    Referal: 'R',
    'Level Pro': 'P',
    'Level Prioritas': 'L'
  } as const;

  type RewardTypeValue = (typeof RewardType)[keyof typeof RewardType];

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

      try {
        const response = await PutData(`${API_URL}/reward/update/${selectedReward}`, formField);

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

          doSaveLogActivity(editActivity);
        } else {
          toast.error('Error Update Reward');
          setAlert({ show: true, message: response?.message });
        }
      } catch (error) {
        toast.error('Something went wrong, please try again.');
      } finally {
        setIsSubmitting(false);
      }
    },
    [selectedReward, formField]
  );

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

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

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

  //   if (
  //     formField.name === '' ||
  //     formField.type === '' ||
  //     formField.amount === 0 ||
  //     formField.status === ''
  //   ) {
  //     setAlert({ show: true, message: 'Please fill in all required fields.' });
  //     return;
  //   }

  //   doUpdateReward(e);
  //   // console.log(formField);
  //   setAlert({ show: false, message: '' });
  // };

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

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

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

            {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 Reward Details...</p>
              </div>
            ) : (
              <form onSubmit={doUpdateReward}>
                <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">
                      Reward Name<span className="text-red-500">*</span>
                    </label>

                    <Input
                      className="input col-span-6"
                      type="text"
                      value={formField.name}
                      onChange={(e) => setFormField((prev) => ({ ...prev, name: e.target.value }))}
                    />
                  </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">
                      Reward Type<span className="text-red-500">*</span>
                    </label>

                    <div className="col-span-6">
                      <Select
                        value={formField.type}
                        onValueChange={(value) =>
                          setFormField((prev) => ({ ...prev, type: value }))
                        }
                      >
                        <SelectTrigger className="w-full">
                          <SelectValue placeholder="Select Type" />
                        </SelectTrigger>
                        <SelectContent>
                          {Object.entries(RewardType).map(
                            ([label, value]: [string, RewardTypeValue]) => (
                              <SelectItem key={value} value={value}>
                                {label}
                              </SelectItem>
                            )
                          )}
                        </SelectContent>
                      </Select>
                    </div>
                  </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">
                      Amount<span className="text-red-500">*</span>
                    </label>

                    <NumericFormat
                      className="input col-span-6"
                      value={formField.amount}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          amount: values.floatValue || 0
                        }));
                      }}
                      placeholder="Enter Amount"
                    />
                  </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 }))
                        }
                      >
                        <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>
                  <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-7" />
                      ) : (
                        'Save Changes'
                      )}
                    </Button>
                  </div>
                </div>
              </form>
            )}
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;
