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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { useManageRewardContext } from '../hooks/useManageRewardContext';

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 [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 doUpdateReward = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();

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

      if (response?.status) {
        resetForm();
        handleEditDialog(false, null);
        toast.success('Success Update Reward');
        reload();
      } else {
        toast.error('Error Update Reward');
        setAlert({ show: true, message: 'Failed to Update Reward. Please try again.' });
      }
    },
    [selectedReward, formField]
  );

  const doFetchData = useCallback(async (id: string) => {
    const response = await GetData(`${API_URL}/reward/getdata/${id}`, { id });
    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
      }));
    }
  }, []);

  // 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(() => {
    // console.log('Selected Reward:', selectedReward);
    if (selectedReward) {
      doFetchData(selectedReward);
    }
  }, [selectedReward]);

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

  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>}

            <form onSubmit={doUpdateReward}>
              <div className="card-body grid gap-5">
                <div className="w-full">
                  <label className="form-label">
                    Name<span className="text-red-500">*</span>
                  </label>

                  <Input
                    className="input"
                    type="text"
                    value={formField.name}
                    onChange={(e) => setFormField((prev) => ({ ...prev, name: e.target.value }))}
                  />
                </div>
                <div className="w-full">
                  <label className="form-label">
                    Type<span className="text-red-500">*</span>
                  </label>

                  <Input
                    className="input"
                    type="text"
                    value={formField.type}
                    onChange={(e) => setFormField({ ...formField, type: e.target.value })}
                  />
                </div>
                <div className="w-full">
                  <label className="form-label">
                    Amount<span className="text-red-500">*</span>
                  </label>

                  <Input
                    className="input"
                    type="number"
                    min={0}
                    step={0.01}
                    value={formField.amount}
                    onChange={(e) => {
                      const value = parseFloat(e.target.value);
                      setFormField({
                        ...formField,
                        amount: isNaN(value) ? 0 : value
                      });
                    }}
                  />
                </div>
                <div className="w-full">
                  <label className="form-label">
                    Status<span className="text-red-500">*</span>
                  </label>

                  <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 className="flex justify-end gap-5">
                  <Button type="button" variant="outline" onClick={resetForm}>
                    Reset
                  </Button>
                  <Button variant="default">Save Changes</Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;
