import { useFormik } from "formik";
import * as Yup from "yup";
import Modal from "../../components/Modals";
import FileDropzone from "../../components/FileDropzone";
import { useState } from "react";

interface Props {
    open: boolean;
    onClose: () => void;
    onSave: (data: any) => void;
    editData?: any;
}

const EditAssignment = ({ open, onClose, onSave, editData }: Props) => {
    const [loading, setLoading] = useState(false);

    const validationSchema = Yup.object({
        type: Yup.string().required("Type is required"),
        title: Yup.string().required("Title is required"),
        description: Yup.string().required("Description is required"),
    });

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: {
            type: editData?.type || "",
            title: editData?.title || "",
            description: editData?.description || "",
            file: null as File | null,
        },
        validationSchema,
        onSubmit: async (values) => {
            setLoading(true);
            await onSave(values);
            setLoading(false);
            onClose();
        },
    });

    // Helper function to safely get files array
    const getFilesArray = () => {
        if (!editData?.files) return [];

        if (Array.isArray(editData.files)) {
            return editData.files;
        }

        if (typeof editData.files === 'string') {
            try {
                const parsed = JSON.parse(editData.files);
                return Array.isArray(parsed) ? parsed : [];
            } catch (e) {
                return [];
            }
        }

        return [];
    };

    const filesArray = getFilesArray();

    if (!open) return null;

    return (
        <Modal
            open={open}
            onClose={onClose}
            title="Edit Assignment"
            maxWidth="max-w-xl"
            footer={
                <>
                    <button onClick={onClose} className="btn btn-outline-danger" type="button" disabled={loading}>
                        Cancel
                    </button>
                    <button onClick={() => formik.handleSubmit()} className="btn btn-primary" type="button" disabled={loading}>
                        {loading ? 'Updating...' : 'Update'}
                    </button>
                </>
            }
        >
            <form className="space-y-4">
                {/* Radio */}
                <div>
                    <label className="block mb-1">Assignment Type <span className='text-danger'>*</span></label>
                    <div className="flex gap-5">
                        <label className="inline-flex items-center gap-2 cursor-pointer">
                            <input
                                type="radio"
                                name="type"
                                value="test"
                                className="form-radio"
                                checked={formik.values.type === "test"}
                                onChange={formik.handleChange}
                            />
                            <span className={formik.values.type === "test" ? "text-primary" : ""}>Test</span>
                        </label>
                        <label className="inline-flex items-center gap-2 cursor-pointer">
                            <input
                                type="radio"
                                name="type"
                                value="project"
                                className="form-radio"
                                checked={formik.values.type === "project"}
                                onChange={formik.handleChange}
                            />
                            <span className={formik.values.type === "project" ? "text-primary" : ""}>Project</span>
                        </label>
                    </div>
                    {formik.touched.type && typeof formik.errors.type === "string" && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.type}</p>
                    )}
                </div>

                {/* Title */}
                <div>
                    <label>Title <span className='text-danger'>*</span></label>
                    <input
                        name="title"
                        className="form-input w-full"
                        value={formik.values.title}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                        disabled={loading}
                    />
                    {formik.touched.title && typeof formik.errors.title === "string" && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.title}</p>
                    )}
                </div>

                {/* Description */}
                <div>
                    <label>Description <span className='text-danger'>*</span></label>
                    <textarea
                        name="description"
                        rows={3}
                        className="form-textarea w-full"
                        value={formik.values.description}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                        disabled={loading}
                    />
                    {formik.touched.description && typeof formik.errors.description === "string" && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.description}</p>
                    )}
                </div>

                {/* File Upload */}
                <div>
                    <label className="block mb-2">Upload New File (Optional)</label>
                    <FileDropzone
                        value={formik.values.file}
                        onChange={(file: File | null) => formik.setFieldValue("file", file)}
                        accept=".pdf,.doc,.docx,.xlsx,.xls,.csv,.jpg,.png"
                        disabled={loading}
                    />
                    {filesArray.length > 0 && (
                        <div className="mt-2">
                            <p className="text-xs text-gray-500 mb-1">Current files:</p>
                            <div className="flex flex-wrap gap-2">
                                {filesArray.map((file: any, idx: number) => (
                                    <span key={idx} className="text-xs bg-gray-100 px-2 py-1 rounded">
                                        {file.name || `File ${idx + 1}`}
                                    </span>
                                ))}
                            </div>
                        </div>
                    )}
                </div>
            </form>
        </Modal>
    );
};

export default EditAssignment;
