import { Formik, FieldArray, FormikErrors, FormikTouched } from "formik";
import * as Yup from "yup";
import { useEffect, useState } from "react";
import Modal from "../../components/Modals";
import IconX from "../../components/Icon/IconX";
import IconPlus from "../../components/Icon/IconPlus";
import Button from "../../components/Buttons";
import Avatar from "../../components/Avatar";
import user from "../../assets/images/auth/user.png";
import api from '../../api/axios';
import { toast } from 'react-toastify';
import config from '../../config';

interface SocialLink {
    social_media: string;
    link: string;
}

interface Props {
    open: boolean;
    onClose: () => void;
    onSave: () => void;
    data?: {
        id: number;
        student_name: string;
        student_code: string;
        profile_photo?: string | null;
        social_links?: SocialLink[] | string; // Allow string or array
    };
}

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

    const validationSchema = Yup.object({
        socialLinks: Yup.array().of(
            Yup.object({
                social_media: Yup.string()
                    .required("Platform name is required")
                    .min(2, "Platform name must be at least 2 characters")
                    .max(50, "Platform name is too long"),
                link: Yup.string()
                    .required("Link is required")
                    .url("Please enter a valid URL (e.g., https://example.com)")
                    .max(500, "Link is too long"),
            })
        ).min(1, "At least one social media link is required"),
    });

    const storageBaseUrl = config.storageUrl;

    const getImageUrl = (imagePath: string | null | undefined): string => {
        if (!imagePath) return user;
        if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
            return imagePath;
        }
        return `${storageBaseUrl}/${imagePath}`;
    };

    // Helper function to parse social links (whether it's string or array)
    const parseSocialLinks = (socialLinks: any): SocialLink[] => {
        if (!socialLinks) return [];

        // If it's already an array, return it
        if (Array.isArray(socialLinks)) {
            return socialLinks;
        }

        // If it's a string, try to parse it
        if (typeof socialLinks === 'string') {
            try {
                const parsed = JSON.parse(socialLinks);
                return Array.isArray(parsed) ? parsed : [];
            } catch (e) {
                console.error("Error parsing social links:", e);
                return [];
            }
        }

        return [];
    };

    // Debug: Log data when component mounts or updates
    useEffect(() => {
        console.log("AddSocialMediaLink - Component rendered");
        console.log("AddSocialMediaLink - open prop:", open);
        console.log("AddSocialMediaLink - data prop:", data);
        console.log("AddSocialMediaLink - student_name:", data?.student_name);
        console.log("AddSocialMediaLink - student_code:", data?.student_code);
        console.log("AddSocialMediaLink - social_links (raw):", data?.social_links);

        // Parse and log the social links
        const parsedLinks = parseSocialLinks(data?.social_links);
        console.log("AddSocialMediaLink - social_links (parsed):", parsedLinks);
    }, [data, open]);

    // Get initial values for form - ensure it's always an array
    const getInitialValues = () => {
        // Parse social links (whether string or array)
        const socialLinks = parseSocialLinks(data?.social_links);

        if (socialLinks.length > 0) {
            return { socialLinks: socialLinks };
        }
        // Always return an array with at least one empty object
        return { socialLinks: [{ social_media: "", link: "" }] };
    };

    // Handle form submission
    const handleSubmit = async (values: { socialLinks: SocialLink[] }) => {
        if (!data?.id) {
            toast.error("Student information is missing");
            return;
        }

        // Filter out empty entries
        const filteredLinks = values.socialLinks.filter(
            link => link.social_media.trim() !== "" && link.link.trim() !== ""
        );

        if (filteredLinks.length === 0) {
            toast.warning("Please add at least one social media link");
            return;
        }

        setLoading(true);
        try {
            const response = await api.post(`/student/${data.id}/social-links`, {
                social_links: filteredLinks
            });

            if (response.data.status === 200 || response.data.status === true) {
                toast.success('Social media links saved successfully');
                onSave();
                onClose();
            } else {
                toast.error(response.data.message || 'Failed to save social media links');
            }
        } catch (error: any) {
            console.error("Error saving social links:", error);
            if (error.response?.data?.errors) {
                const errors = error.response.data.errors;
                Object.keys(errors).forEach(key => {
                    toast.error(errors[key][0]);
                });
            } else {
                toast.error(error.response?.data?.message || 'Failed to save social media links');
            }
        } finally {
            setLoading(false);
        }
    };

    // Don't render if no data or modal is closed
    if (!open) return null;
    if (!data) {
        console.log("No data provided to modal");
        return null;
    }

    // Log initial values for debugging
    const initialValues = getInitialValues();
    console.log("Initial values:", initialValues);

    return (
        <Modal
            open={open}
            onClose={onClose}
            title="Manage Social Media Links"
            maxWidth="max-w-2xl"
            footer={
                <>
                    <button
                        onClick={onClose}
                        className="btn btn-outline-danger"
                        type="button"
                        disabled={loading}
                    >
                        Cancel
                    </button>
                    <button
                        type="submit"
                        form="social-media-form"
                        className="btn btn-primary"
                        disabled={loading}
                    >
                        {loading ? "Saving..." : "Save All Links"}
                    </button>
                </>
            }
        >
            <Formik
                key={`social-media-form-${data.id}`}
                initialValues={initialValues}
                validationSchema={validationSchema}
                onSubmit={handleSubmit}
                enableReinitialize={true}
            >
                {(formik) => {
                    // Debug formik values
                    console.log("Formik values socialLinks:", formik.values.socialLinks);
                    console.log("Is socialLinks an array?", Array.isArray(formik.values.socialLinks));

                    return (
                        <form
                            id="social-media-form"
                            onSubmit={formik.handleSubmit}
                            className="space-y-6 max-h-[550px] overflow-y-auto pr-2"
                        >
                            <FieldArray name="socialLinks">
                                {(arrayHelpers) => (
                                    <div className="space-y-4">
                                        {/* Student Info Header */}
                                        <div className="flex justify-between items-center pb-4 border-b">
                                            <div className="flex items-center gap-3">
                                                <Avatar
                                                    src={getImageUrl(data.profile_photo)}
                                                    size="lg"
                                                />
                                                <div>
                                                    <div className="text-base font-semibold">
                                                        {data.student_name || "Student Name"}
                                                    </div>
                                                    <div className="text-xs text-gray-500">
                                                        ID: {data.student_code || "STU000"}
                                                    </div>
                                                </div>
                                            </div>
                                            <Button
                                                variant="secondary"
                                                type="button"
                                                className="text-sm"
                                                onClick={() => arrayHelpers.push({ social_media: "", link: "" })}
                                                disabled={loading}
                                            >
                                                <IconPlus className="w-4 h-4 mr-1" />
                                                Add Another Link
                                            </Button>
                                        </div>

                                        {/* Social Links Form Fields */}
                                        {Array.isArray(formik.values.socialLinks) && formik.values.socialLinks.length > 0 ? (
                                            formik.values.socialLinks.map((_, index) => {
                                                const touchedLink = (formik.touched.socialLinks as FormikTouched<SocialLink>[] | undefined)?.[index];
                                                const errorsLink = (formik.errors.socialLinks as FormikErrors<SocialLink>[] | undefined)?.[index];

                                                return (
                                                    <div
                                                        key={index}
                                                        className="border border-gray-200 rounded-xl p-5 bg-white relative hover:shadow-sm transition-shadow"
                                                    >
                                                        <div className="grid grid-cols-12 gap-4">
                                                            <div className="col-span-5">
                                                                <label className="block mb-2 font-medium text-sm">
                                                                    Platform Name <span className='text-red-500'>*</span>
                                                                </label>
                                                                <input
                                                                    type="text"
                                                                    className="form-input w-full"
                                                                    placeholder="e.g., Facebook, Twitter, LinkedIn"
                                                                    disabled={loading}
                                                                    {...formik.getFieldProps(`socialLinks.${index}.social_media`)}
                                                                />
                                                                {touchedLink?.social_media && errorsLink?.social_media && (
                                                                    <p className="text-red-500 text-xs mt-1">
                                                                        {errorsLink.social_media}
                                                                    </p>
                                                                )}
                                                            </div>
                                                            <div className="col-span-5">
                                                                <label className="block mb-2 font-medium text-sm">
                                                                    Link <span className='text-red-500'>*</span>
                                                                </label>
                                                                <input
                                                                    type="url"
                                                                    className="form-input w-full"
                                                                    placeholder="https://..."
                                                                    disabled={loading}
                                                                    {...formik.getFieldProps(`socialLinks.${index}.link`)}
                                                                />
                                                                {touchedLink?.link && errorsLink?.link && (
                                                                    <p className="text-red-500 text-xs mt-1">
                                                                        {errorsLink.link}
                                                                    </p>
                                                                )}
                                                            </div>
                                                            <div className="col-span-2 flex items-end">
                                                                {formik.values.socialLinks.length > 1 && (
                                                                    <button
                                                                        type="button"
                                                                        onClick={() => arrayHelpers.remove(index)}
                                                                        className="text-gray-400 hover:text-red-600 transition-colors bg-gray-100 hover:bg-red-50 rounded-lg px-3 py-2 mb-0.5"
                                                                        disabled={loading}
                                                                    >
                                                                        <IconX className="w-4 h-4" />
                                                                    </button>
                                                                )}
                                                            </div>
                                                        </div>
                                                    </div>
                                                );
                                            })
                                        ) : (
                                            <div className="text-center py-8 text-gray-400">
                                                <p>No social media links added</p>
                                                <Button
                                                    variant="secondary"
                                                    type="button"
                                                    className="mt-2"
                                                    onClick={() => arrayHelpers.push({ social_media: "", link: "" })}
                                                >
                                                    <IconPlus className="w-4 h-4 mr-1" />
                                                    Add Your First Link
                                                </Button>
                                            </div>
                                        )}

                                        {/* Form Errors */}
                                        {formik.errors.socialLinks && typeof formik.errors.socialLinks === 'string' && (
                                            <p className="text-red-500 text-sm text-center">
                                                {formik.errors.socialLinks}
                                            </p>
                                        )}
                                    </div>
                                )}
                            </FieldArray>
                        </form>
                    );
                }}
            </Formik>
        </Modal>
    );
};

export default AddSocialMediaLink;
