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';
import { RefreshCw } from 'lucide-react';
import { initialStateReward, validateFormReward } from './Types';

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 [errors, setErrors] = useState<Record<string, string>>({});

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

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

  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();
      setIsSubmitting(true);

      try {
        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(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 (!validateFormReward(formField, setErrors)) {
      return;
    }

    doCreateReward(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>Reward - Create</DialogTitle>
          <DialogDescription />
        </DialogHeader>
        <DialogBody ref={parentRef}>
          <div className="flex flex-col">
            <form onSubmit={handleSubmit}>
              <div className="card-body grid gap-5">
                {/* Reward Name */}
                <div className="grid grid-cols-8 gap-2 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 ${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>

                {/* Reward Type */}
                <div className="grid grid-cols-8 gap-2 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 }));
                        setErrors((prev) => ({ ...prev, type: '' }));
                      }}
                    >
                      <SelectTrigger className={`w-full ${errors.type ? 'border-red-500' : ''}`}>
                        <SelectValue placeholder="Select Type" />
                      </SelectTrigger>
                      <SelectContent>
                        {Object.entries(RewardType).map(
                          ([label, value]: [string, RewardTypeValue]) => (
                            <SelectItem key={value} value={value}>
                              {label}
                            </SelectItem>
                          )
                        )}
                      </SelectContent>
                    </Select>
                  </div>
                  {errors.type && (
                    <span className="text-red-500 text-xs mt-1 col-span-8 ml-[calc(25%+0.5rem)]">
                      {errors.type}
                    </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">
                    Amount<span className="text-red-500">*</span>
                  </label>
                  <NumericFormat
                    className={`input col-span-6 ${errors.amount ? 'border-red-500' : ''}`}
                    value={formField.amount}
                    thousandSeparator="."
                    decimalSeparator=","
                    allowNegative={false}
                    onValueChange={(values) => {
                      setFormField((prev) => ({
                        ...prev,
                        amount: values.floatValue ?? null
                      }));
                      setErrors((prev) => ({ ...prev, amount: '' }));
                    }}
                    placeholder="Enter Amount"
                  />
                  {errors.amount && (
                    <span className="text-red-500 text-xs mt-1 col-span-8 ml-[calc(25%+0.5rem)]">
                      {errors.amount}
                    </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;
