import React, { useState, useEffect, useContext } from 'react';
import axios from 'axios';
import Swal from 'sweetalert2';
import { ConfigContext } from '../../Context/ConfigContext';
import { useParams } from 'react-router-dom';

const RequestForm = () => {
    const { unique_access_token } = useParams();
    const { apiURL } = useContext(ConfigContext);

    const [loading, setLoading] = useState(true);
    const [submitting, setSubmitting] = useState(false);
    const [requestData, setRequestData] = useState(null);
    const [items, setItems] = useState([]);
    const [uploadedItems, setUploadedItems] = useState([]);
    const [formValues, setFormValues] = useState({});
    const [fileValues, setFileValues] = useState({});
    const [accessError, setAccessError] = useState(null);

    useEffect(() => {
        GetRequestData();
    }, [unique_access_token]);

    const GetRequestData = async () => {
        try {
            setLoading(true);
            const response = await axios.get(`${apiURL}api/requirements/requests/access/${unique_access_token}`);

            if (response.data.success) {
                setRequestData(response.data.data);
                setItems(response.data.data.items || []);
                setUploadedItems(response.data.data.uploaded_items || []);
                setAccessError(null);
            } else {
                setAccessError(response.data.message || 'Invalid access token');
            }
        } catch (error) {
            console.log(error);
            if (error.response) {
                setAccessError(error.response.data.message || 'Access denied');
            } else {
                setAccessError('Failed to fetch request data');
            }
        } finally {
            setLoading(false);
        }
    };

    const handleInputChange = (itemId, value) => {
        setFormValues({
            ...formValues,
            [itemId]: value
        });
    };

    const handleFileChange = (itemId, file) => {
        setFileValues({
            ...fileValues,
            [itemId]: file
        });
    };

    const submitItem = async (itemId) => {
        const value = formValues[itemId] || '';
        const file = fileValues[itemId];

        if (!value && !file) {
            Swal.fire({
                icon: 'warning',
                title: 'Missing Information',
                text: 'Please provide a value or upload a document'
            });
            return;
        }

        try {
            setSubmitting(true);

            const formData = new FormData();
            formData.append('requirements_request_id', requestData.request.requirements_request_id);
            formData.append('requirement_id', requestData.requirement.requirement_id);
            formData.append('requirements_item_id', itemId);

            if (value) {
                formData.append('requirements_request_item_value', value);
            }

            if (file) {
                formData.append('document', file);
            }

            const response = await axios.post(`${apiURL}api/requirements/requests/items`, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'Accept': 'application/json'
                }
            });

            if (response.data.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Submitted Successfully',
                    text: 'Your item has been submitted',
                    timer: 3000,
                    timerProgressBar: true
                });

                await GetRequestData();

                setFormValues({
                    ...formValues,
                    [itemId]: ''
                });
                setFileValues({
                    ...fileValues,
                    [itemId]: null
                });
            }
        } catch (error) {
            console.log(error);
            Swal.fire({
                icon: 'error',
                title: 'Submission Failed',
                text: error.response?.data?.message || 'Failed to submit item'
            });
        } finally {
            setSubmitting(false);
        }
    };

    const deleteItem = async (submittedItemId) => {
        const result = await Swal.fire({
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, delete it!'
        });

        if (!result.isConfirmed) return;

        try {
            const response = await axios.delete(`${apiURL}api/requirements/requests/items/${submittedItemId}`, {
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            });

            if (response.data.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Deleted Successfully',
                    text: 'Item has been removed'
                });
                await GetRequestData();
            }
        } catch (error) {
            console.log(error);
            Swal.fire({
                icon: 'error',
                title: 'Delete Failed',
                text: error.response?.data?.message || 'Failed to delete item'
            });
        }
    };

    if (loading) {
        return (
            <div className="d-flex justify-content-center align-items-center vh-100 bg-light">
                <div className="text-center">
                    <div className="spinner-border text-primary" role="status">
                        <span className="visually-hidden">Loading...</span>
                    </div>
                    <p className="mt-2 text-muted">Loading request data...</p>
                </div>
            </div>
        );
    }

    if (accessError) {
        return (
            <div className="d-flex justify-content-center align-items-center vh-100 bg-light">
                <div className="card shadow" style={{ maxWidth: '450px' }}>
                    <div className="card-body text-center p-4">
                        <div className="text-danger mb-3">
                            <svg width="48" height="48" fill="currentColor" viewBox="0 0 16 16">
                                <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z" />
                                <path d="M7.002 11a1 1 0 1 1 2 0 1 1 0 0 1-2 0zM7.1 4.995a.905.905 0 1 1 1.8 0l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 4.995z" />
                            </svg>
                        </div>
                        <h5>Access Denied</h5>
                        <p className="text-muted small">{accessError}</p>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div
            className="min-vh-100 py-5"
            style={{
                background: "#f4f7fb"
            }}
        >
            <div className="container" style={{ maxWidth: "950px" }}>
                {/* Header */}
                <div className="card border-0 shadow-sm mb-4">
                    <div className="card-body text-center py-5">

                        <div
                            className="rounded-circle bg-dark-subtle shadow-sm d-inline-flex align-items-center justify-content-center mb-4 border"
                            style={{ width: 130, height: 130 }}
                        >
                            <img
                                src="https://admin.atctransline.in/assets/images/new_logo.png"
                                alt="logo"
                                className="img-fluid"
                                style={{
                                    maxWidth: "70%",
                                    maxHeight: "70%",
                                    objectFit: "contain"
                                }}
                            />
                        </div>

                        <h2 className="fw-bold mb-2">
                            Document Submission Portal
                        </h2>

                        <p className="text-muted mb-0">
                            Please upload the requested documents below.
                            Your files are securely submitted.
                        </p>

                    </div>
                </div>

                {/* <div className="card border-0 shadow-sm mb-4">

                    <div className="card-body">

                        <h5 className="fw-bold mb-4">
                            Request Details
                        </h5>

                        <div className="row">

                            <div className="col-md-6 mb-3">
                                <small className="text-muted">
                                    Requirement
                                </small>

                                <div className="fw-semibold">
                                    {requestData.requirement.requirement_title}
                                </div>
                            </div>

                            <div className="col-md-6 mb-3">
                                <small className="text-muted">
                                    Status
                                </small>

                                <div>

                                    <span className={`badge ${requestData.request.requirements_request_status === 1
                                        ? "bg-warning text-dark"
                                        : "bg-success"
                                        }`}>
                                        {requestData.request.requirements_request_status === 1
                                            ? "Pending"
                                            : "Completed"}
                                    </span>

                                </div>
                            </div>

                            <div className="col-md-12">

                                <small className="text-muted">
                                    Description
                                </small>

                                <div>
                                    {requestData.requirement.requirement_description}
                                </div>

                            </div>

                        </div>

                    </div>

                </div> */}

                {/* Progress Stats */}
                <div className="card border-0 shadow-sm mb-4">

                    <div className="card-body">

                        <div className="d-flex justify-content-between mb-2">

                            <strong>Document Progress</strong>

                            <small>
                                {uploadedItems.length} / {items.length}
                            </small>

                        </div>

                        <div
                            className="progress"
                            style={{ height: 10 }}
                        >
                            <div
                                className="progress-bar"
                                style={{
                                    width: `${(uploadedItems.length / items.length) * 100}%`
                                }}
                            ></div>
                        </div>

                    </div>

                </div>

                {/* Items List */}
                {items.length === 0 ? (
                    <div className="card shadow-sm border-0">
                        <div className="card-body text-center py-5">
                            <p className="text-muted mb-0">No items required for this request.</p>
                        </div>
                    </div>
                ) : (
                    items.map((item) => {
                        const isUploaded = uploadedItems.some(
                            uploaded => uploaded.requirements_item_id === item.requirements_item_id
                        );
                        const uploadedItem = uploadedItems.find(
                            uploaded => uploaded.requirements_item_id === item.requirements_item_id
                        );

                        return (
                            <div key={item.requirements_item_id} className="card shadow-sm border-0 mb-3">
                                <div className="card-body">
                                    <div className="d-flex justify-content-between">

                                        <div>

                                            <h5 className="fw-bold mb-1">

                                                <i className="ri-file-list-3-line text-primary me-2"></i>

                                                {item.requirements_item_title}

                                            </h5>

                                            <p className="text-muted mb-0">
                                                {item.requirements_item_description}
                                            </p>

                                        </div>

                                        <div>

                                            {isUploaded ?

                                                <span className="badge bg-success">
                                                    Uploaded
                                                </span>

                                                :

                                                <span className="badge bg-warning text-dark">
                                                    Pending
                                                </span>

                                            }

                                        </div>

                                    </div>

                                    {!isUploaded ? (
                                        <div>
                                            <div className="mb-2">
                                                <input
                                                    type="text"
                                                    className="form-control form-control-sm"
                                                    placeholder={`Enter value for ${item.requirements_item_title}`}
                                                    value={formValues[item.requirements_item_id] || ''}
                                                    onChange={(e) => handleInputChange(item.requirements_item_id, e.target.value)}
                                                    disabled={submitting}
                                                />
                                            </div>
                                            <div className="mb-2">
                                                <label className="border rounded p-4 text-center w-100 bg-light">

                                                    <i
                                                        className="ri-upload-cloud-2-line text-primary"
                                                        style={{ fontSize: 34 }}
                                                    ></i>

                                                    <div className="fw-semibold">

                                                        Click to choose document

                                                    </div>

                                                    <small className="text-muted">

                                                        PDF, JPG, PNG, DOC

                                                    </small>

                                                    <input
                                                        hidden
                                                        type="file"
                                                        onChange={(e) =>
                                                            handleFileChange(
                                                                item.requirements_item_id,
                                                                e.target.files[0]
                                                            )
                                                        }
                                                    />

                                                </label>
                                                {fileValues[item.requirements_item_id] && (
                                                    <small className="text-success d-block mt-1">
                                                        {fileValues[item.requirements_item_id].name}
                                                    </small>
                                                )}
                                            </div>
                                            <button
                                                className="btn btn-primary w-100 mt-3"
                                                onClick={() => submitItem(item.requirements_item_id)}
                                            >
                                                <i className="ri-upload-cloud-line me-2"></i>


                                                Upload Document
                                            </button>
                                        </div>
                                    ) : (
                                        <div>
                                            <div className="alert alert-success mb-3">

                                                <i className="ri-checkbox-circle-fill me-2"></i>

                                                Document uploaded successfully.

                                            </div>

                                            <div className="border rounded p-3 bg-light">

                                                <p className="mb-1">

                                                    <strong>Value</strong>

                                                </p>
                                                <div className="d-flex gap-2 align-items-center">
                                                    <div>

                                                        <p className='mb-0'>

                                                            {uploadedItem.requirements_request_item_value || "-"}

                                                        </p>
                                                    </div>


                                                    <button
                                                        className="btn btn-danger btn-sm"
                                                        onClick={() => deleteItem(uploadedItem.requirements_request_item_id)}
                                                    >
                                                        <i className="ri-delete-bin-line"></i>
                                                    </button>

                                                </div>

                                            </div>
                                        </div>
                                    )}
                                </div>
                            </div>
                        );
                    })
                )}

                {/* Submitted Items Summary */}
                {/* {uploadedItems.length > 0 && (
                    <div className="card shadow-sm border-0 mt-4">
                        <div className="card-body">
                            <h6 className="mb-3">Submitted Items</h6>
                            <div className="row g-2">
                                {uploadedItems.map((item, index) => (
                                    <div key={index} className="col-md-6">
                                        <div className="d-flex justify-content-between align-items-center bg-light p-2 rounded">
                                            <small className="fw-semibold">
                                                {items.find(i => i.requirements_item_id === item.requirements_item_id)?.requirements_item_title || 'Item'}
                                            </small>
                                            <small className="text-success">✓ Submitted</small>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                )} */}
            </div>
        </div>
    );
};

export default RequestForm;