import { useFormik } from "formik";
import * as Yup from "yup";
import Modal from "../../components/Modals";
import { useState } from "react";
import IconCalendar from "../../components/Icon/IconCalendar";
import IconMapPin from "../../components/Icon/IconMapPin";
import IconTarget from "../../components/Icon/IconTarget";
import Badge from "../../components/Badge";
import FileDropzone from "../../components/FileDropzone";
import IconDownload from "../../components/Icon/IconDownload";
import api from "../../api/axios";
import { toast } from "react-toastify";

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

const AddEventLead = ({ open, onClose, onSave, event }: Props) => {
    const [uploading, setUploading] = useState(false);

    // Format date for display
    const formatDate = (date: string) => {
        if (!date) return 'N/A';
        return new Date(date).toLocaleDateString('en-US', {
            day: '2-digit',
            month: 'short',
            year: 'numeric'
        });
    };

    //  Validation Schema
    const validationSchema = Yup.object({
        file: Yup.mixed()
            .required("File is required")
            .test("fileType", "Only Excel files (.xlsx, .xls, .csv) are allowed", (value: any) => {
                if (!value) return false;
                const allowedTypes = [
                    "application/vnd.ms-excel",
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    "text/csv",
                    "application/csv",
                ];
                return allowedTypes.includes(value.type) ||
                       /\.(xlsx|xls|csv)$/i.test(value.name);
            })
            .test("fileSize", "File too large (max 5MB)", (value: any) => {
                if (!value) return false;
                return value.size <= 5 * 1024 * 1024; // 5MB
            }),
    });

    //  Formik Setup
    const formik = useFormik({
        initialValues: {
            file: null as File | null,
        },
        validationSchema,
        onSubmit: async (values) => {
            if (!values.file) return;

            setUploading(true);

            try {
                const formData = new FormData();
                formData.append('file', values.file);
                formData.append('marketing_event_id', event.id.toString());

                const response = await api.post('/marketing/bulk-upload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                });

                if (response.data.status) {
                    // Show detailed results
                    const { success_count, skipped_count, skipped_rows } = response.data.data;

                    let message = `Successfully added ${success_count} leads to ${event.event_name || event.name}`;
                    if (skipped_count > 0) {
                        message += `\n\nSkipped ${skipped_count} entries:\n`;
                        skipped_rows.forEach((row: any) => {
                            message += `\n• Row ${row.row}: ${row.reason}`;
                        });
                    }

                    toast.success(message, {
                        autoClose: 5000,
                        closeOnClick: true,
                    });

                    onSave(response.data.data);
                    onClose();
                    formik.resetForm();
                } else {
                    toast.error(response.data.message || 'Failed to upload leads');
                }
            } catch (error: any) {
                console.error('Upload error:', error);
                const errorMsg = error.response?.data?.message || 'Failed to upload leads. Please check your file format.';
                toast.error(errorMsg);
            } finally {
                setUploading(false);
            }
        },
    });

    return (
        <Modal
            open={open}
            onClose={() => {
                onClose();
                formik.resetForm();
            }}
            title="Add Leads to Event"
            maxWidth="max-w-3xl"
            footer={
                <>
                    <button
                        onClick={() => {
                            onClose();
                            formik.resetForm();
                        }}
                        className="btn btn-outline-danger"
                        disabled={uploading}
                    >
                        Cancel
                    </button>

                    <button
                        className="btn btn-primary"
                        onClick={() => formik.handleSubmit()}
                        disabled={uploading}
                    >
                        {uploading ? (
                            <>
                                <span className="animate-spin mr-2">⏳</span>
                                Uploading...
                            </>
                        ) : (
                            'Upload & Add Leads'
                        )}
                    </button>
                </>
            }
        >
            {/* Event Info */}
            <div className="mb-4 p-4 border rounded-lg bg-gray-50">
                <div className="flex items-center justify-between gap-2">
                    <h3 className="text-lg font-semibold mb-2">{event?.event_name || event?.name}</h3>
                    <Badge
                        color={event.status === "UPCOMING" ? "info" : event.status === "COMPLETED" ? "success" : "warning"}
                        variant="outline"
                        className="text-xs"
                        rounded
                    >
                        {event.status}
                    </Badge>
                </div>

                <div className="text-sm text-gray-500 mt-1 flex flex-wrap gap-4">
                    <span className="flex gap-1 items-center">
                        <IconCalendar className="w-4 h-4" />
                        {formatDate(event.start_date)} - {formatDate(event.end_date)}
                    </span>
                    <span className="flex gap-1 items-center">
                        <IconMapPin className="w-4 h-4" />
                        {event.location}
                    </span>
                    <span className="flex gap-1 items-center">
                        <IconTarget className="w-4 h-4" />
                        Target: {event.target_lead || 0} Leads
                    </span>
                    <span>|</span>
                    <span>Current Leads: {event.leads_count || 0}</span>
                </div>
            </div>

            {/* Instructions */}
            <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                <h4 className="font-semibold text-blue-800 mb-2">📋 Instructions:</h4>
                <ul className="text-sm text-blue-700 list-disc list-inside space-y-1">
                    <li>Download the sample Excel file to see the correct format</li>
                    <li>Required columns: <strong>name</strong> and <strong>mobile</strong></li>
                    <li>Mobile numbers will be checked for duplicates</li>
                    <li>Existing leads will be automatically skipped</li>
                    <li>Maximum file size: 5MB</li>
                </ul>
            </div>

            {/* Download Sample */}
            <div className="flex justify-end mb-3">
                <a
                    href="/samples/Lead_Bulk_Upload.xlsx"
                    download
                    className="flex items-center gap-2 text-sm text-primary hover:underline"
                >
                    <IconDownload className="w-4 h-4" />
                    Download Sample Excel Template
                </a>
            </div>

            {/* File Upload */}
            <div>
                <label className="block mb-2 font-medium">
                    Upload Excel File <span className="text-red-500">*</span>
                </label>

                <FileDropzone
                    value={formik.values.file}
                    onChange={(file) => {
                        formik.setFieldValue("file", file, true);
                        formik.setFieldTouched("file", true, false);
                    }}
                    accept=".xlsx,.xls,.csv"
                    disabled={uploading}
                />

                {formik.touched.file && formik.errors.file && (
                    <p className="text-red-500 text-xs mt-1">
                        {formik.errors.file as string}
                    </p>
                )}

                <p className="text-xs text-gray-500 mt-2">
                    Supported formats: .xlsx, .xls, .csv
                </p>
            </div>
        </Modal>
    );
};

export default AddEventLead;
