import React, { useContext, useEffect, useState } from 'react'
import { useParams, Link } from 'react-router-dom'
import { ConfigContext } from '../Context/ConfigContext'
import axios from 'axios'
import { DateFormaterMonth } from '../Components/GlobalFunctions'
import ProgressPieChart from '../Components/ProgressPieChart'
import JSZip from 'jszip'
import Swal from 'sweetalert2'
import { jsPDF } from 'jspdf'
import 'jspdf-autotable'

// Make sure to import autoTable correctly
import autoTable from 'jspdf-autotable'

const getRequestStatus = (status) => {
    switch (status) {
        case 0: return { text: 'Pending', color: 'warning' };
        case 1: return { text: 'Approved', color: 'success' };
        case 2: return { text: 'Rejected', color: 'danger' };
        case 3: return { text: 'Revised', color: 'info' };
        default: return { text: 'Unknown', color: 'secondary' };
    }
};

// Currency formatter for QAR
const formatCurrency = (value) =>
    new Intl.NumberFormat('en-QA', { style: 'currency', currency: 'QAR' }).format(value);

const StatusBadge = ({ status }) => {
    const { text, color } = getRequestStatus(status)
    return <span className={`badge bg-${color}`}>{text}</span>
}

const PreviewProject = () => {
    const { project_id } = useParams()
    const { apiHeaderJson, apiURL } = useContext(ConfigContext)
    const headers = apiHeaderJson

    const [project, setProject] = useState(null)
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState(null)
    const [downloading, setDownloading] = useState(false)

    const GetProjectDetails = async () => {
        try {
            setLoading(true)
            const response = await axios.get(`${apiURL}api/project/information`, {
                headers,
                params: { project_id }
            })

            if (response.data.success) {
                const projectData = response.data.data.project;
                const consultants = response.data.data.consultants || [];
                const contractors = response.data.data.contractors || [];
                const items = response.data.data.items || [];
                const media = response.data.data.media || [];
                const requests = response.data.data.requests || [];

                const structuredData = {
                    project_title: projectData.project_title || "Not specified",
                    project_address: projectData.project_address || "Not specified",
                    profile_name: projectData.profile_name || "Not specified",
                    profile_contact_number: projectData.profile_contact_number || "Not specified",
                    profile_email: projectData.profile_email || "Not specified",
                    budget: projectData.budget || "Not specified",
                    project_start_date: projectData.project_start_date || "",
                    project_end_date: projectData.project_end_date || "",
                    project_description: projectData.project_description || "",
                    project_status: projectData.project_status || 0,

                    contractors,
                    consultants,
                    items,
                    media,
                    requests
                };

                setProject(structuredData)
            } else {
                setError('Failed to fetch project details')
            }
        } catch (error) {
            console.error('Error fetching project details:', error)
            setError('Error fetching project details')
        } finally {
            setLoading(false)
        }
    }

    const downloadArchive = () => {
        const fileUrl = `https://tms.atctransline.in/apis/public/archives/${project_id}_archive/${project_id}_archive.zip`;

        const link = document.createElement("a");
        link.href = fileUrl;
        link.setAttribute("download", `${project_id}_archive.zip`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };

    const RequestArchive = async () => {
        try {
            setDownloading(true);

            Swal.fire({
                title: "Preparing Archive",
                text: "Please wait while we generate your ZIP...",
                allowOutsideClick: false,
                didOpen: () => Swal.showLoading()
            });

            const response = await axios.post(
                `${apiURL}api/projects/archive`,
                { project_id },
                { headers }
            );

            if (!response.data.success) {
                throw new Error(response.data.message);
            }

            // Wait if backend needs a second
            await new Promise(resolve => setTimeout(resolve, 1500));

            await downloadArchive();

            Swal.fire({
                icon: "success",
                title: "Download Completed",
                text: "Your archive has been downloaded.",
                timer: 2000,
                showConfirmButton: false
            });

        } catch (error) {
            Swal.fire({
                icon: "error",
                title: "Download Failed",
                text: error.message || "Unable to generate archive."
            });
        } finally {
            setDownloading(false);
        }
    };

    useEffect(() => {
        GetProjectDetails()
    }, [project_id])

    if (loading) {
        return (
            <div className="main-content">
                <div className="page-content">
                    <div className="container-fluid">
                        <div className="text-center py-5">
                            <div className="spinner-border text-primary" role="status">
                                <span className="visually-hidden">Loading...</span>
                            </div>
                            <p className="mt-2">Loading project details...</p>
                        </div>
                    </div>
                </div>
            </div>
        )
    }

    if (error || !project) {
        return (
            <div className="main-content">
                <div className="page-content">
                    <div className="container-fluid">
                        <div className="alert alert-danger" role="alert">
                            {error || 'Project not found'}
                        </div>
                        <Link to="/archives" className="btn btn-primary">
                            Back to Archives
                        </Link>
                    </div>
                </div>
            </div>
        )
    }

    // Filter media by type
    const imageMedia = project.media.filter(m => m.pm_type === 'IMAGE');
    const documentMedia = project.media.filter(m => m.pm_type === 'DOCUMENT');

    return (
        <div className="main-content">
            <div className="page-content">
                <div className="container-fluid">
                    <div className="row mb-3">
                        <div className="col-12">
                            <div className="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 className="mb-sm-0">Project Completion Report</h4>
                                <div className="page-title-right">
                                    <ol className="breadcrumb m-0">
                                        <li className="breadcrumb-item">
                                            <Link to="/dashboard">Dashboard</Link>
                                        </li>
                                        <li className="breadcrumb-item">
                                            <Link to="/archives">Archives</Link>
                                        </li>
                                        <li className="breadcrumb-item active">Preview Project</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Download Button */}
                    <div className="row mb-3">
                        <div className="col-12">
                            <button
                                onClick={RequestArchive}
                                disabled={downloading}
                                className="btn btn-success btn-label"
                                style={{ float: "right" }}
                            >
                                <i className="ri-folder-zip-fill label-icon"></i>

                                {downloading ? "Preparing..." : "Download Zip"}
                            </button>
                        </div>
                    </div>

                    <div className="row">
                        <div className="col-12">
                            <div className="card">
                                <div className="card-body">
                                    <div className="mb-4 border-bottom pb-2">
                                        <div className="row">
                                            <div className="col-md-8">
                                                <h3>New Line Company</h3>
                                                <p style={{ color: "#1a4e5a" }}>Building Dreams, Crafting Realities</p>
                                            </div>
                                            <div className="col-md-4">
                                                <img
                                                    src="/assets/images/new_logo.png"
                                                    alt="Company Logo"
                                                    className='img-fluid float-end w-25'
                                                />
                                            </div>
                                        </div>
                                        <div className="text-center">
                                            <h2>Project Completion Report</h2>
                                        </div>
                                    </div>

                                    {/* Project Information Section */}
                                    <div className="mb-4">
                                        <h6 className="border-bottom pb-2 mb-3 fs-5" style={{ color: "#1a4e5a" }}>Project Information</h6>
                                        <div className="row">
                                            <div className="col-md-6 mb-2">
                                                <strong>Project Name:</strong> {project.project_title}
                                            </div>
                                            <div className="col-md-6 mb-2">
                                                <strong>Project Status:</strong> <span className="badge bg-success ms-1">Completed</span>
                                            </div>
                                            <div className="col-md-6 mb-2">
                                                <strong>Location:</strong> {project.project_address}
                                            </div>
                                            <div className="col-md-6 mb-2">
                                                <strong>Client:</strong> {project.profile_name}
                                            </div>
                                            <div className="col-md-6 mb-2">
                                                <strong>Contact:</strong> {project.profile_contact_number}
                                            </div>
                                            <div className="col-md-6 mb-2">
                                                <strong>Email:</strong> {project.profile_email}
                                            </div>
                                            <div className="col-md-6 mb-2">
                                                <strong>Start Date:</strong> {DateFormaterMonth(project.project_start_date)}
                                            </div>
                                            <div className="col-md-6 mb-2">
                                                <strong>Completion Date:</strong> {DateFormaterMonth(project.project_end_date)}
                                            </div>
                                            {project.project_description && (
                                                <div className="col-12 mb-2">
                                                    <strong>Description:</strong> {project.project_description}
                                                </div>
                                            )}
                                        </div>
                                    </div>

                                    {/* Project Progress Chart */}
                                    <div className="mb-4">
                                        <h6 className="border-bottom pb-2 mb-3 fs-5" style={{ color: "#1a4e5a" }}>
                                            Project Progress
                                        </h6>

                                        <div className="row">
                                            <div className="col-md-6">
                                                <ProgressPieChart project_id={project_id} />
                                            </div>
                                            <div className="col-md-6 d-flex flex-column justify-content-center">
                                                <h6 className="mb-3" style={{ color: "#1a4e5a" }}>
                                                    Overview
                                                </h6>

                                                <p className="mb-2">
                                                    This chart represents the overall execution status of the project
                                                    based on recorded material usage and planned quantities.
                                                </p>

                                                <ul className="mb-3 ps-3">
                                                    <li>Shows current project movement in real time</li>
                                                    <li>Helps identify whether work is on track</li>
                                                    <li>Useful for client and management reports</li>
                                                </ul>

                                                <div className="fst-italic text-muted small">
                                                    *The data is synced automatically from the project management system.
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Consultants Section */}
                                    <div className="mb-4">
                                        <h6 className="border-bottom pb-2 mb-3 fs-5" style={{ color: "#1a4e5a" }}>Consultants</h6>
                                        {project.consultants?.length > 0 ? (
                                            <div className="table-responsive">
                                                <table className="table table-bordered table-sm">
                                                    <thead className="table-light">
                                                        <tr>
                                                            <th>Name</th>
                                                            <th>Company</th>
                                                            <th>Contact</th>
                                                            <th>Email</th>
                                                            <th>Role</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {project.consultants.map((consultant, index) => (
                                                            <tr key={index}>
                                                                <td>{consultant.profile_name || "N/A"}</td>
                                                                <td>{consultant.profile_about || "N/A"}</td>
                                                                <td>{consultant.profile_contact_number || "N/A"}</td>
                                                                <td>{consultant.profile_email || "N/A"}</td>
                                                                <td>{consultant.profile_category_name || "N/A"}</td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </table>
                                            </div>
                                        ) : (
                                            <p>No consultants available</p>
                                        )}
                                    </div>

                                    {/* Contractors Section */}
                                    <div className="mb-4">
                                        <h6 className="border-bottom pb-2 mb-3 fs-5" style={{ color: "#1a4e5a" }}>Contractors</h6>
                                        {project.contractors?.length > 0 ? (
                                            <div className="table-responsive">
                                                <table className="table table-bordered table-sm">
                                                    <thead className="table-light">
                                                        <tr>
                                                            <th>Name</th>
                                                            <th>Company</th>
                                                            <th>Contact</th>
                                                            <th>Email</th>
                                                            <th>Role</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {project.contractors.map((contractor, index) => (
                                                            <tr key={index}>
                                                                <td>{contractor.profile_name || "N/A"}</td>
                                                                <td>{contractor.profile_about || "N/A"}</td>
                                                                <td>{contractor.profile_contact_number || "N/A"}</td>
                                                                <td>{contractor.profile_email || "N/A"}</td>
                                                                <td>{contractor.profile_category_name || "N/A"}</td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </table>
                                            </div>
                                        ) : (
                                            <p>No contractors available</p>
                                        )}
                                    </div>

                                    {/* Items Section */}
                                    <div className="mb-4">
                                        <h6 className="border-bottom pb-2 mb-3 fs-5" style={{ color: "#1a4e5a" }}>Project Items</h6>
                                        {project.items?.length > 0 ? (
                                            <div className="table-responsive">
                                                <table className="table table-bordered table-sm">
                                                    <thead className="table-light">
                                                        <tr>
                                                            <th>Item Name</th>
                                                            <th>Description</th>
                                                            <th>Quantity</th>
                                                            <th>Price</th>
                                                            <th>Total</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {project.items.map((item, index) => (
                                                            <tr key={index}>
                                                                <td>{item.item_name || "N/A"}</td>
                                                                <td>{item.item_description || "N/A"}</td>
                                                                <td>{item.pi_item_qty || "N/A"}</td>
                                                                <td>{item.pi_item_price ? formatCurrency(item.pi_item_price) : "N/A"}</td>
                                                                <td>
                                                                    {item.pi_item_qty && item.pi_item_price
                                                                        ? formatCurrency(item.pi_item_qty * item.pi_item_price)
                                                                        : "N/A"}
                                                                </td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </table>
                                            </div>
                                        ) : (
                                            <p>No items available</p>
                                        )}
                                    </div>

                                    {/* Submittals Section */}
                                    <div className="mb-4">
                                        <h6 className="border-bottom pb-2 mb-3 fs-5" style={{ color: "#1a4e5a" }}>Submittals</h6>
                                        {project.requests?.length > 0 ? (
                                            project.requests.map((request, index) => (
                                                <div key={index} className="card mb-2">
                                                    <div className="card-body">
                                                        <div className="row">
                                                            <div className="col-md-6 mb-1">
                                                                <strong>Request ID:</strong> {request.project_request_id}
                                                            </div>
                                                            <div className="col-md-6 mb-1">
                                                                <strong>Status:</strong> <StatusBadge status={request.request_status} />
                                                            </div>
                                                            <div className="col-md-12 mb-1">
                                                                <strong>Description:</strong> {request.submittal_description}: {request.request_brief_description}
                                                            </div>
                                                            <div className="col-md-6 mb-1">
                                                                <strong>Item:</strong> {request.item_name}
                                                            </div>
                                                            <div className="col-md-6 mb-1">
                                                                <strong>Date:</strong> {DateFormaterMonth(request.request_date)}
                                                            </div>
                                                            <div className="col-md-6 mb-1">
                                                                <strong>Requested By:</strong> {request.requested_by || "Unknown"}
                                                            </div>
                                                            <div className="col-md-6 mb-1">
                                                                <strong>Status Updated By:</strong> {request.status_updated_by || "Unknown"}
                                                            </div>
                                                            {request.request_status === 3 && (
                                                                <div className="col-md-6 mb-1">
                                                                    <strong>Revised By:</strong> {request.revised_by || "Unknown"}
                                                                </div>
                                                            )}
                                                        </div>
                                                    </div>
                                                </div>
                                            ))
                                        ) : (
                                            <p>No submittals available</p>
                                        )}
                                    </div>

                                    {/* Documents Section */}
                                    {documentMedia.length > 0 && (
                                        <div className="mb-4">
                                            <h6 className="border-bottom pb-2 mb-3 fs-5" style={{ color: "#1a4e5a" }}>Project Documents</h6>
                                            <div className="row">
                                                {documentMedia.map((media, index) => (
                                                    <div key={index} className="col-md-4 mb-3">
                                                        <div className="card">
                                                            <div className="card-body text-center">
                                                                <i className="bx bx-file display-4 text-muted"></i>
                                                                <h6 className="card-title mt-2">{media.pm_title || "Untitled Document"}</h6>
                                                                <a
                                                                    href={`https://tms.atctransline.in/apis/public/documents/${media.pm_file_name}`}
                                                                    target="_blank"
                                                                    rel="noopener noreferrer"
                                                                    className="btn btn-primary btn-sm"
                                                                >
                                                                    View Document
                                                                </a>
                                                            </div>
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    )}

                                    {/* Pictures Section */}
                                    <div>
                                        <h6 className="border-bottom pb-2 mb-3 fs-5" style={{ color: "#1a4e5a" }}>Project Images</h6>
                                        {imageMedia.length > 0 ? (
                                            <div className="row">
                                                {imageMedia.map((media, index) => (
                                                    <div key={index} className="col-md-4 mb-3">
                                                        <div className="card">
                                                            <img
                                                                src={`https://tms.atctransline.in/apis/public/images/${media.pm_file_name.replace(/\s+/g, '%20')}`}
                                                                className="card-img-top"
                                                                alt={media.pm_title || "Project image"}
                                                                style={{ height: '200px', objectFit: 'cover' }}
                                                            />
                                                            <div className="card-body">
                                                                <p className="card-text text-center">
                                                                    {media.pm_title || "Untitled"}
                                                                </p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                        ) : (
                                            <p>No images available</p>
                                        )}
                                    </div>
                                </div>
                            </div>
                            <Link to="/archives" className="btn btn-secondary btn-label">
                                <i className='ri-arrow-left-line align-middl label-icon'></i> Back
                            </Link>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default PreviewProject