import React, { useState, useEffect } from "react";
import { FaFileAlt } from "react-icons/fa";
import { useTheme } from "../contexts/ThemeContext";
import FormsHeader from "../components/Forms/FormsHeader";
import FormsMessage from "../components/Forms/FormsMessage";
import FormsTable from "../components/Forms/FormsTable";
import DeleteConfirmationModal from "../components/Forms/DeleteConfirmationModal";
import { buildApiUrl, API_ENDPOINTS } from "../utils/config";

const FormsPage = () => {
  const [kickoffForms, setKickoffForms] = useState([]);
  const [error, setError] = useState(null);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [selectedForm, setSelectedForm] = useState(null);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const { isLight } = useTheme();

  // Theme-based styling classes
  const cardBgClass = isLight
    ? "bg-white border border-yellow-200 shadow-md hover:shadow-lg"
    : "bg-gradient-to-br from-gray-800 to-slate-800 border border-gray-700 shadow-lg hover:shadow-xl";

  const buttonClass = isLight
    ? "bg-gradient-to-r from-yellow-500 to-amber-500 hover:from-yellow-600 hover:to-amber-600 text-white"
    : "bg-gradient-to-r from-gray-600 to-slate-600 hover:from-gray-500 hover:to-slate-500 text-white";

  // Safe data validation function
  const validateFormData = (data) => {
    try {
      if (!data || !Array.isArray(data)) {
        console.log("Data is not an array, using fallback");
        return [];
      }

      return data
        .filter((form) => {
          if (!form || typeof form !== "object") {
            console.warn("Invalid form object:", form);
            return false;
          }
          return true;
        })
        .map((form) => ({
          id: String(form.id || Math.random()),
          project_type: String(form.project_type || "Unknown Project"),
          form: String(form.form || "/uploads/kickoff_forms/default.docx"),
        }));
    } catch (err) {
      console.error("Error validating form data:", err);
      return [];
    }
  };

  // Fetch kickoff forms from API
  const fetchKickoffForms = async () => {
    try {
      setError(null);
      console.log("Fetching kickoff forms...");

      const response = await fetch(buildApiUrl(API_ENDPOINTS.KICKOFF_FORM));
      console.log("Response status:", response.status);

      if (!response.ok) {
        throw new Error(`Failed to fetch kickoff forms: ${response.status}`);
      }

      const result = await response.json();
      console.log("API response:", result);

      // Handle different response structures safely
      let formsData = [];
      try {
        if (result && result.success && Array.isArray(result.data)) {
          formsData = result.data;
        } else if (Array.isArray(result)) {
          formsData = result;
        } else if (result && result.data && Array.isArray(result.data)) {
          formsData = result.data;
        } else {
          console.log("Unexpected response structure, using fallback data");
          formsData = [];
        }
      } catch (parseErr) {
        console.error("Error parsing response:", parseErr);
        formsData = [];
      }

      // Validate and set forms
      const validatedForms = validateFormData(formsData);
      console.log("Validated forms:", validatedForms);
      setKickoffForms(validatedForms);
    } catch (err) {
      console.error("Error fetching kickoff forms:", err);
      setError(String(err.message || "Unknown error"));

      // Fallback to mock data if API fails
      console.log("Using fallback mock data...");
      const fallbackForms = [
        {
          id: "1",
          project_type: "E-commerce Platform",
          form: "/uploads/kickoff_forms/kickoff_form_123.docx",
        },
        {
          id: "2",
          project_type: "Mobile App Development",
          form: "/uploads/kickoff_forms/kickoff_form_124.docx",
        },
      ];
      setKickoffForms(fallbackForms);
    }
  };

  // Download kickoff form
  const handleDownload = async (formId) => {
    try {
      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.KICKOFF_FORM_DOWNLOAD(formId)),
        {
          method: "GET",
        }
      );

      if (!response.ok) {
        throw new Error("Failed to download form");
      }

      // Get filename from response headers
      const contentDisposition = response.headers.get("content-disposition");
      let filename = "kickoff_form.docx";
      if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename="(.+)"/);
        if (filenameMatch) {
          filename = filenameMatch[1];
        }
      }

      // Create blob and download
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (err) {
      console.error("Error downloading form:", err);
      // Silent failure - no alert shown
    }
  };

  // Delete kickoff form - open confirmation modal
  const handleDelete = (formId) => {
    const form = kickoffForms.find(f => f.id == formId);
    if (form) {
      setSelectedForm(form);
      setIsDeleteModalOpen(true);
    }
  };

  // Handle delete confirmation
  const handleDeleteConfirm = async (form) => {
    try {
      setDeleteLoading(true);
      
      // Store original forms for potential restoration
      const originalForms = [...kickoffForms];
      
      // Immediately remove the form from the local state for instant UI feedback
      const updatedForms = kickoffForms.filter(f => f.id != form.id);
      setKickoffForms(updatedForms);
      
      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.KICKOFF_FORM_BY_ID(form.id)),
        {
          method: "DELETE",
        }
      );

      if (!response.ok) {
        throw new Error("Failed to delete form");
      }

      const result = await response.json();
      if (result.success) {
        // Success - form is already removed from UI
        setIsDeleteModalOpen(false);
        setSelectedForm(null);
      } else {
        // If deletion failed, restore the form to the list
        setKickoffForms(originalForms);
        throw new Error(result.message || "Failed to delete form");
      }
    } catch (err) {
      console.error("Error deleting form:", err);
      // Restore the form to the list if there was an error
      setKickoffForms(originalForms);
      // Silent failure - no alert shown
    } finally {
      setDeleteLoading(false);
    }
  };

  // Handle delete modal close
  const handleDeleteClose = () => {
    setIsDeleteModalOpen(false);
    setSelectedForm(null);
  };

  // Add new kickoff form
  const handleAddForm = async (formData) => {
    try {
      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.KICKOFF_FORM_UPLOAD),
        {
          method: "POST",
          body: formData,
        }
      );

      if (!response.ok) {
        throw new Error("Failed to add form");
      }

      const result = await response.json();
      if (result.success) {
        // Refresh the forms list
        await fetchKickoffForms();
        // Success - form is already added to the list
      } else {
        throw new Error(result.message || "Failed to add form");
      }
    } catch (err) {
      console.error("Error adding form:", err);
      // Silent failure - no alert shown
      throw err;
    }
  };

  // Fetch forms on component mount
  useEffect(() => {
    fetchKickoffForms();
  }, []);



  if (error) {
    return (
      <div className="space-y-3 max-w-full overflow-hidden px-2 sm:px-4 lg:px-6">
        <div className={`${cardBgClass} rounded-xl p-6 text-center`}>
          <div className="text-red-600 mb-4">
            <FaFileAlt className="mx-auto h-12 w-12" />
          </div>
          <h3 className="text-lg font-semibold text-red-800 mb-2">
            Error Loading Forms
          </h3>
          <p className="text-red-600 mb-4">{String(error)}</p>
          <button
            onClick={fetchKickoffForms}
            className={`px-4 py-2 ${buttonClass} rounded-lg transition-all duration-200 hover:scale-105`}
          >
            Try Again
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-3 max-w-full overflow-hidden px-2 sm:px-4 lg:px-6">
      <FormsHeader onAddForm={handleAddForm} />
      <FormsMessage />
      <FormsTable
        kickoffForms={kickoffForms}
        onDownload={handleDownload}
        onDelete={handleDelete}
      />

      {/* Delete Confirmation Modal */}
      <DeleteConfirmationModal
        isOpen={isDeleteModalOpen}
        onClose={handleDeleteClose}
        onConfirm={handleDeleteConfirm}
        form={selectedForm}
        loading={deleteLoading}
      />
    </div>
  );
};

export default FormsPage;
