import { useFormik } from 'formik';
import * as Yup from 'yup';
import { useState } from 'react';
import Modal from '../../components/Modals';
import FileDropzone from '../../components/FileDropzone';
import api from '../../api/axios';
import { toast } from 'react-toastify';

interface Props {
    open: boolean;
    onClose: () => void;
    onSave: (data: any) => void;
    staffId?: number; // Add staffId prop
}

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

    const validationSchema = Yup.object({
        doc_name: Yup.string()
            .required('Document name is required')
            .min(3, 'Document name must be at least 3 characters'),
        file: Yup.mixed()
            .required('File is required')
            .test('fileSize', 'File size must be less than 10MB', (value) => {
                if (!value) return true;
                return (value as File).size <= 10 * 1024 * 1024;
            })
            .test('fileType', 'Only PDF, DOC, DOCX, PNG, JPG files are allowed', (value) => {
                if (!value) return true;
                const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/png', 'image/jpeg'];
                return allowedTypes.includes((value as File).type);
            }),
    });

    const formik = useFormik({
        initialValues: {
            doc_name: '',
            file: null as File | null,
        },
        validationSchema,
        onSubmit: async (values) => {
            if (!staffId) {
                toast.error('Staff ID is missing');
                return;
            }

            setLoading(true);
            try {
                const formData = new FormData();
                formData.append('name', values.doc_name);
                formData.append('document', values.file as File);

                const response = await api.post(`/staff/document/${staffId}`, formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                });

                if (response.data.status) {
                    toast.success('Document uploaded successfully');
                    onSave(response.data.data);
                    formik.resetForm();
                    onClose();
                }
            } catch (error: any) {
                console.error('Upload failed:', error);
                toast.error(error.response?.data?.message || 'Failed to upload document');
            } finally {
                setLoading(false);
            }
        },
    });

    // Reset form when modal closes
    const handleClose = () => {
        formik.resetForm();
        onClose();
    };

    return (
        <Modal
            open={open}
            onClose={handleClose}
            title="Upload Document"
            footer={
                <>
                    <button
                        onClick={handleClose}
                        className="btn btn-outline-danger"
                        type="button"
                        disabled={loading}
                    >
                        Cancel
                    </button>
                    <button
                        onClick={() => formik.handleSubmit()}
                        className="btn btn-primary"
                        type="button"
                        disabled={loading}
                    >
                        {loading ? 'Uploading...' : 'Upload Document'}
                    </button>
                </>
            }
        >
            <form className="space-y-4">
                {/* Document Name */}
                <div>
                    <label className="block mb-1 font-medium">
                        Document Name <span className="text-red-500">*</span>
                    </label>
                    <input
                        type="text"
                        className="form-input w-full"
                        placeholder="Enter document name (e.g., Offer Letter, Aadhaar Card)"
                        {...formik.getFieldProps('doc_name')}
                        disabled={loading}
                    />
                    {formik.touched.doc_name && formik.errors.doc_name && (
                        <p className="text-red-500 text-sm mt-1">
                            {formik.errors.doc_name as string}
                        </p>
                    )}
                </div>

                {/* Dropzone File Upload */}
                <div>
                    <label className="block mb-2 font-medium">
                        Upload File <span className="text-red-500">*</span>
                    </label>
                    <FileDropzone
                        value={formik.values.file}
                        onChange={(file) => formik.setFieldValue('file', file)}
                        accept=".pdf,.doc,.docx,.png,.jpg,.jpeg"
                        disabled={loading}
                    />
                    <p className="text-xs text-gray-500 mt-1">
                        Accepted formats: PDF, DOC, DOCX, PNG, JPG (Max size: 10MB)
                    </p>
                    {formik.touched.file && formik.errors.file && (
                        <p className="text-red-500 text-sm mt-1">
                            {formik.errors.file as string}
                        </p>
                    )}
                </div>
            </form>
        </Modal>
    );
};

export default UploadDocument;
