import React, { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import axiosInstance from "../../../utils/axiosConfig";
import { FORMS_URL, FORMS_TYPE_URL } from "../../../utils/config";
import "./styles/FormPreview.css";

const FormPreview = () => {
  const navigate = useNavigate();
  const { id } = useParams();
  const [formData, setFormData] = useState(null);
  const [formTypes, setFormTypes] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchFormData = async () => {
      try {
        setLoading(true);
        const [formRes, formTypesRes] = await Promise.all([
          axiosInstance.get(`${FORMS_URL}/${id}`),
          axiosInstance.get(FORMS_TYPE_URL),
        ]);

        if (formRes.data.success && formRes.data.data) {
          setFormData(formRes.data.data);
        } else {
          setError("Failed to load form details.");
        }

        setFormTypes(formTypesRes.data.data || []);
      } catch (error) {
        console.error("Error fetching form details:", error);
        setError("Failed to load form details. Please try again.");
      } finally {
        setLoading(false);
      }
    };
    console.log("formData", formData);

    if (id) {
      fetchFormData();
    }
  }, [id]);

  const getFormTypeName = (typeId) => {
    if (!typeId) return "Unknown";
    const formType = formTypes.find((t) => t.form_type_id === typeId);
    return formType ? formType.form_type : "Unknown";
  };

  const formatDate = (dateString) => {
    if (!dateString) return "Not set";
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  };

  const handleBack = () => {
    navigate("/view-forms");
  };

  const handlePrint = () => {
    window.print();
  };

  if (loading) {
    return (
      <div style={{ padding: "2rem", textAlign: "center" }}>
        <p>Loading form...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ padding: "2rem", textAlign: "center" }}>
        <p>{error}</p>
        <button onClick={handleBack}>Back to Forms List</button>
      </div>
    );
  }

  if (!formData) {
    return (
      <div style={{ padding: "2rem", textAlign: "center" }}>
        <p>Form not found</p>
        <button onClick={handleBack}>Back to Forms List</button>
      </div>
    );
  }

  return (
    <>
      {/* Action Bar - Hidden when printing */}
      <div className="preview-actions no-print">
        <button className="btn-back" onClick={handleBack}>
          <svg
            width="1.125rem"
            height="1.125rem"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M19 12H5M12 19l-7-7 7-7" />
          </svg>
          <span className="btn-text">Back to Forms List</span>
        </button>
        <button className="btn-print" onClick={handlePrint}>
          <svg
            width="1.125rem"
            height="1.125rem"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <polyline points="6 9 6 2 18 2 18 9"></polyline>
            <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"></path>
            <rect x="6" y="14" width="12" height="8"></rect>
          </svg>
          <span className="btn-text">Print Form</span>
        </button>
      </div>

      <div className="form-details-view-container">
        {/* Form Name */}
        <div className="form-name-section">
          <h1 className="form-name-title">{formData.title}</h1>
          {formData.description && (
            <p className="form-name-description">{formData.description}</p>
          )}
        </div>

        {/* Form Type, Date, Location Row */}
        <div className="form-info-row">
          <div className="form-info-item">
            <span className="form-info-label">Type:</span>
            <span className="form-info-value">
              {formData.form_type || getFormTypeName(formData.form_type_id)}
            </span>
          </div>
          <div className="form-info-item">
            <span className="form-info-label">Date:</span>
            <span className="form-info-value">
              {formData.end_date
                ? formatDate(formData.end_date)
                : formData.created_date
                ? formatDate(formData.created_date)
                : "Not set"}
            </span>
          </div>
          {formData.locations && formData.locations.length > 0 && (
            <div className="form-info-item">
              <span className="form-info-label">Location:</span>
              <span className="form-info-value">
                {formData.locations.map((loc) => loc.location_name).join(", ")}
              </span>
            </div>
          )}
        </div>

        {/* Form Details Section */}
        {formData.end_date && (
          <div className="form-details-section">
            <div className="form-details-grid">
              <div className="form-detail-item">
                <div className="detail-content">
                  <span className="detail-label">End Date</span>
                  <span className="detail-value">
                    {formatDate(formData.end_date)}
                  </span>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Questions Section */}
        <div className="questions-section">
          <h2 className="questions-heading">Questions</h2>
          {console.log("formData.sat_questions", formData.sat_questions)}

          {!formData.sat_questions || formData.sat_questions.length === 0 ? (
            <div className="empty-questions-state">
              <h3>No Questions</h3>
              <p>This form doesn't have any questions assigned yet.</p>
            </div>
          ) : (
            <div className="questions-list">
              {formData.sat_questions.map((sat_question, index) => (
                <div key={sat_question.question_id} className="question-card">
                  <p className="question-text">
                    {index + 1}. {sat_question.question}
                  </p>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Form Footer Info */}
        <div className="form-header-info">
          <div className="form-id-info">
            <span className="form-id-label">Form ID:</span>
            <span className="form-id-value">{formData.form_id}</span>
          </div>
          {formData.created_by_name && (
            <div className="form-creator-info">
              <span className="form-creator-label">Created By:</span>
              <span className="form-creator-value">
                {formData.created_by_name}
              </span>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

export default FormPreview;
