import React, { useEffect, useState } from "react";
import { useForm, SubmitHandler } from "react-hook-form";
import { Dialog, DialogActions, DialogContent, DialogTitle, Button, TextField, MenuItem, Select, InputLabel, FormControl, FormHelperText, Box } from "@mui/material";
import { useDropzone } from 'react-dropzone';

// Define the types for form data
interface FormData {
  exerciseName: string;
  description: string;
  primMuscleTargeted: string;
  secMuscleTargeted?: string;
  repsOrduration: string;
  sets: string;
  restBetweenSets?: string;
  difficultyLevel: "beginner" | "intermediate" | "advanced";
  formTips?: string;
  modificationOptions?: string;
  equipmentNeeded?: string;
  videoLink?: string;
  audioInstructions?: string;
  restTimeAfterExercise?: string;
  totalTimeForExercise?: string;
  progressTracking?: string;
  motivationalTips?: string;
  exerciseImage?: File | null; 
}

interface AddEditExerciseModalProps {
  open: boolean;
  handleClose: () => void;
  editRow: any;
  preview: string;
  setPreview: string;
}

const AddEditExerciseModal: React.FC<AddEditExerciseModalProps> = ({ open, handleClose, editRow ,preview,setPreview}) => {
  const { handleSubmit, register, formState: { errors }, setValue, reset, getValues} = useForm<FormData>();
  const { getRootProps, getInputProps } = useDropzone({
    accept: 'image/*, .gif', 
    onDrop: (acceptedFiles) => {
      if (acceptedFiles && acceptedFiles.length > 0) {
        setValue('exerciseImage', acceptedFiles[0]); 
        handlePreview(acceptedFiles[0])
      }
    },
  });
console.log("Imageeeee" , getValues('exerciseImage'))
  // State to store the preview URL of the uploaded file
 
  const [selectedFile, setSelectedFile] = useState<File | null>(null);

  useEffect(() => {
    if (editRow) {
      setValue('exerciseName', editRow.exerciseName);
      setValue('description', editRow.description);
      setValue('primMuscleTargeted', editRow.primMuscleTargeted);
      setValue('secMuscleTargeted', editRow.secMuscleTargeted);
      setValue('repsOrduration', editRow.repsOrduration);
      setValue('sets', editRow.sets);
      setValue('restBetweenSets', editRow.restBetweenSets);
      setValue('difficultyLevel', editRow.difficultyLevel);
      if (editRow.exerciseImage) {
        setValue('exerciseImage', editRow.exerciseImage);
        setPreview(editRow.exerciseImage); 
        setSelectedFile(editRow.exerciseImage); 
      }
    } else {
      reset();
      setPreview(null); 
      setSelectedFile(null);
    }
  }, [editRow, setValue, reset,setPreview]);

  const onSubmit: SubmitHandler<FormData> = (data: FormData) => {
    console.log(data); 
    reset();
    setPreview(null); 
    handleClose();
  };

  
  const handlePreview = (file: File | null) => {
    if (file) {
      setValue('exerciseImage', file); 
      setPreview(URL.createObjectURL(file)); 
      setSelectedFile(file);
    } else {
      setPreview(null); 
      setSelectedFile(null); 
    }
  };

  
  const handleClearFile = () => {
    setPreview(null);
    setSelectedFile(null);
    setValue('exerciseImage', null); 
  };

  return (
    <Dialog open={open} onClose={handleClose} fullWidth maxWidth="md">
      <DialogTitle>Create Exercise</DialogTitle>
      <DialogContent>
        <form onSubmit={handleSubmit(onSubmit)}>
          <Box sx={{ display: "grid", gap: 2 }}>
            {/* Exercise Name */}
            <TextField
              fullWidth
              label="Exercise Name"
              variant="outlined"
              {...register("exerciseName", { required: "Exercise name is required" })}
              error={!!errors.exerciseName}
              helperText={errors.exerciseName?.message}
            />

            {/* Description */}
            <TextField
              fullWidth
              label="Description"
              variant="outlined"
              multiline
              rows={4}
              {...register("description", { required: "Description is required" })}
              error={!!errors.description}
              helperText={errors.description?.message}
            />

            {/* Primary Muscles Targeted */}
            <TextField
              fullWidth
              label="Primary Muscles Targeted"
              variant="outlined"
              {...register("primMuscleTargeted", { required: "Primary muscles are required" })}
              error={!!errors.primMuscleTargeted}
              helperText={errors.primMuscleTargeted?.message}
            />

            {/* Secondary Muscles Targeted */}
            <TextField
              fullWidth
              label="Secondary Muscles Targeted"
              variant="outlined"
              {...register("secMuscleTargeted")}
            />

            {/* Reps/Duration */}
            <TextField
              fullWidth
              label="Reps/Duration"
              variant="outlined"
              {...register("repsOrduration", { required: "Reps or duration is required" })}
              error={!!errors.repsOrduration}
              helperText={errors.repsOrduration?.message}
            />

            {/* Sets */}
            <TextField
              fullWidth
              label="Sets"
              variant="outlined"
              {...register("sets", { required: "Sets are required" })}
              error={!!errors.sets}
              helperText={errors.sets?.message}
            />

            {/* Rest Between Sets */}
            <TextField
              fullWidth
              label="Rest Between Sets"
              variant="outlined"
              {...register("restBetweenSets")}
            />

            {/* Difficulty Level */}
            <FormControl fullWidth error={!!errors.difficultyLevel}>
              <InputLabel>Difficulty Level</InputLabel>
              <Select
                defaultValue={editRow?.difficultyLevel || ''}
                label="Difficulty Level"
                {...register("difficultyLevel", { required: "Difficulty level is required" })}
              >
                <MenuItem value="beginner">Beginner</MenuItem>
                <MenuItem value="intermediate">Intermediate</MenuItem>
                <MenuItem value="advanced">Advanced</MenuItem>
              </Select>
              {errors.difficultyLevel && <FormHelperText>{errors.difficultyLevel.message}</FormHelperText>}
            </FormControl>

            {/* Image/GIF Upload */}
            <Box {...getRootProps()} sx={{ border: '2px dashed', padding: 2, width: '100%', marginBottom: 2 }}>
              <input {...getInputProps()} onChange={(e) => handlePreview(e.target.files?.[0] || null)} />
              <p>Drag & drop an image or GIF here, or click to select</p>
            </Box>

            {/* Preview the uploaded image or GIF */}
            {preview && (
              <Box sx={{ textAlign: 'center', marginBottom: 2 }}>
                <p>Preview:</p>
                <img src={preview} alt="Exercise Preview" style={{ maxWidth: '100%', maxHeight: 300, objectFit: 'contain' }} />
                <p>{selectedFile?.name || selectedFile.split("/").pop()}</p> 
              
                <Button variant="outlined" color="secondary" onClick={handleClearFile} sx={{ marginTop: 1 }}>
                  Remove File
                </Button>
              </Box>
            )}
          </Box>
        </form>
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="secondary">
          Cancel
        </Button>
        <Button onClick={handleSubmit(onSubmit)} color="primary" variant="contained">
          Submit
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default AddEditExerciseModal;
