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

const API_URL = apiConfig.service_master_data;

const AddDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showAddDialog, handleAddDialog } = useManageRewardContext();
  const { reload } = useDataGrid();
  const { PostData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });

  const initialState = {
    name: '',
    type: '',
    amount: 0,
    status: '',
    created_by: '',
    created_at: ''
  };

  const [formField, setFormField] = useState(initialState);
  const created_time = new Date();
  const formattedTime = created_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 doCreateReward = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      // console.log('Data yang akan dikirim:', formField);
      const response = await PostData(`${API_URL}/reward/create`, formField);

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

        doSaveLogActivity(createActivity);
      } else {
        toast.error('Failed to create reward.');
        setAlert({ show: true, message: 'Failed to create reward. Please try again.' });
      }
    },
    [formField]
  );

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

    if (
      formField.name.trim() === '' ||
      formField.type.trim() === '' ||
      formField.amount === 0 ||
      formField.status.trim() === ''
    ) {
      setAlert({ show: true, message: 'Please fill name field.' });
      return;
    }

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

  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={(open) => handleAddDialog(open)}>
      <DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
        <DialogHeader>
          <DialogTitle>Reward - Create</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody ref={parentRef}>
          <div className="flex flex-col">
            {alert.show && <Alert variant="danger">{alert.message}</Alert>}
            <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">
                    Name<span className="text-red-500">*</span>
                  </label>

                  <Input
                    className="input col-span-6"
                    type="text"
                    autoComplete="off"
                    value={formField.name}
                    onChange={({ target }) =>
                      setFormField((prev) => ({ ...prev, name: 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">
                    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" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Y">Active</SelectItem>
                        <SelectItem value="N">InActive</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <div className="flex justify-end gap-5">
                  <Button type="button" variant="outline" onClick={resetForm}>
                    Reset
                  </Button>
                  <Button variant="default" type="submit">
                    Save Change
                  </Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default AddDialog;
