import { useFormik } from "formik";
import * as Yup from "yup";
import Modal from "../../components/Modals";
import Select from "../../components/Select";
import { useEffect, useState } from "react";
import api from '../../api/axios';
import TagInput from "../../components/TagInput";

interface Props {
    open: boolean;
    onClose: () => void;
    onSave: (id: number, data: any) => Promise<boolean>;
    data: any;
}
type OptionType = {
  value: string;
  label: string;
};
const EditCourse = ({ open, onClose, onSave, data }: Props) => {
    const [categories, setCategories] = useState<OptionType[]>([]);
    const [loading, setLoading] = useState(false);

    const validationSchema = Yup.object({
        course_name: Yup.string()
            .required("Course name is required")
            .min(3, "Course name must be at least 3 characters"),
        course_code: Yup.string()
            .required("Course code is required")
            .min(3, "Course code must be at least 3 characters"),
        skills: Yup.array()
            .min(1, "At least one skill is required")
            .required("Skills are required"),
        course_category_id: Yup.number()
            .required("Category is required"),
        duration: Yup.string()
            .required("Duration is required"),
        fees: Yup.number()
            .min(0, "Fee must be positive")
            .required("Fee is required"),
        leave_limit: Yup.number()
            .min(0, "Leave limit must be positive")
            .required("Leave limit is required"),
        description: Yup.string().nullable(),
    });

    // Helper function to parse skills from various formats - MOVED ABOVE formik
    const parseSkills = (skills: any): string[] => {
        if (!skills) return [];
        if (Array.isArray(skills)) return skills;
        try {
            const parsed = JSON.parse(skills);
            return Array.isArray(parsed) ? parsed : [];
        } catch {
            // If it's a comma-separated string
            return skills.split(',').map((s: string) => s.trim()).filter(Boolean);
        }
    };

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: {
            course_name: data?.course_name || data?.title || "",
            course_code: data?.course_code || "",
            skills: parseSkills(data?.skills) || [], // Now parseSkills is defined before this
            course_category_id: data?.course_category_id || "",
            duration: data?.duration || "",
            fees: data?.fees || "",
            leave_limit: data?.leave_limit || "",
            description: data?.description || "",
        },
        validationSchema,
        onSubmit: async (values, { setSubmitting }) => {
            setSubmitting(true);
            try {
                const success = await onSave(data?.id, values);
                if (success) {
                    onClose();
                }
            } catch (error) {
                console.error('Error updating course:', error);
            } finally {
                setSubmitting(false);
            }
        },
    });

    // Fetch categories from API
    useEffect(() => {
        const fetchCategories = async () => {
            setLoading(true);
            try {
                const response = await api.get('/category/list');
                if (response.data.status === 200) {
                    const categoryOptions = response.data.data.map((cat: any) => ({
                        value: cat.id,
                        label: cat.name
                    }));
                    setCategories(categoryOptions);
                }
            } catch (error) {
                console.error('Error fetching categories:', error);
            } finally {
                setLoading(false);
            }
        };

        if (open) {
            fetchCategories();
        }
    }, [open]);

    // Reset form when modal closes
    useEffect(() => {
        if (!open) {
            formik.resetForm();
        }
    }, [open]);

    return (
        <Modal
            open={open}
            onClose={onClose}
            title="Edit Course"
            maxWidth="max-w-2xl"
            footer={
                <>
                    <button
                        onClick={onClose}
                        className="btn btn-outline-danger"
                        type="button"
                        disabled={formik.isSubmitting}
                    >
                        Cancel
                    </button>
                    <button
                        onClick={() => formik.handleSubmit()}
                        className="btn btn-primary"
                        type="button"
                        disabled={formik.isSubmitting}
                    >
                        {formik.isSubmitting ? "Saving..." : "Save Changes"}
                    </button>
                </>
            }
        >
            <form className="grid grid-cols-12 gap-4">
                <div className="col-span-12">
                    <label className="block mb-1 font-medium">Course Name <span className="text-danger">*</span></label>
                    <input
                        name="course_name"
                        className="form-input w-full"
                        value={formik.values.course_name}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                        placeholder="Enter course name"
                    />
                    {formik.touched.course_name && formik.errors.course_name && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.course_name as string}</p>
                    )}
                </div>

                <div className="col-span-12">
                    <label className="block mb-1 font-medium">Category <span className="text-danger">*</span></label>
                    <Select
                        options={categories}
                        isLoading={loading}
                        value={categories.find(o => o.value === formik.values.course_category_id)}
                        onChange={(val: any) => {
                            formik.setFieldValue("course_category_id", val?.value || "");
                            formik.setFieldTouched("course_category_id", true);
                        }}
                        placeholder="Select category"
                    />
                    {formik.touched.course_category_id && formik.errors.course_category_id && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.course_category_id as string}</p>
                    )}
                </div>

                <div className="col-span-6">
                    <label className="block mb-2">Course Code <span className="text-danger">*</span></label>
                    <input
                        name="course_code"
                        className="form-input w-full"
                        value={formik.values.course_code}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                        placeholder="e.g., CR-2516"
                    />
                    {formik.touched.course_code && formik.errors.course_code && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.course_code as string}</p>
                    )}
                </div>

                <div className="col-span-6">
                    <label className="block mb-1 font-medium">Duration <span className="text-danger">*</span></label>
                    <input
                        name="duration"
                        className="form-input w-full"
                        value={formik.values.duration}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                        placeholder="e.g., 6 Months"
                    />
                    {formik.touched.duration && formik.errors.duration && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.duration as string}</p>
                    )}
                </div>

                <div className="col-span-6">
                    <label className="block mb-1 font-medium">Fees (₹) <span className="text-danger">*</span></label>
                    <input
                        name="fees"
                        type="number"
                        className="form-input w-full"
                        value={formik.values.fees}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                        placeholder="Course fees"
                    />
                    {formik.touched.fees && formik.errors.fees && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.fees as string}</p>
                    )}
                </div>

                <div className="col-span-6">
                    <label className="block mb-1 font-medium">Leave Limit (days) *</label>
                    <input
                        name="leave_limit"
                        type="number"
                        className="form-input w-full"
                        value={formik.values.leave_limit}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                        placeholder="Number of leaves allowed"
                    />
                    {formik.touched.leave_limit && formik.errors.leave_limit && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.leave_limit as string}</p>
                    )}
                </div>

                <div className="md:col-span-12">
                    <label>Skill Tags <span className="text-danger">*</span></label>
                    <TagInput
                        label="Skills"
                        value={formik.values.skills}
                        onChange={(newTags: string[]) => {
                            formik.setFieldValue("skills", newTags);
                            formik.setFieldTouched("skills", true);
                        }}
                        placeholder="Add skills..."
                    />
                    {formik.touched.skills && formik.errors.skills && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.skills as string}</p>
                    )}
                </div>

                <div className="col-span-12">
                    <label className="block mb-1 font-medium">Description</label>
                    <textarea
                        name="description"
                        rows={3}
                        className="form-textarea w-full"
                        value={formik.values.description}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                        placeholder="Enter course description (optional)"
                    />
                </div>
            </form>
        </Modal>
    );
};

export default EditCourse;
