// File Path: monorepo/web/frontend/src/pages/Admin/EventContract/Add/Step3Page.jsx

import React, { useState, useEffect, useCallback } from "react";
import { Link, useNavigate } from "react-router";
import {
  useEventContractWizardStorage,
  useAttachmentManager,
} from "../../../../services/Services";
import {
  Button,
  Card,
  Alert,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  ChevronRightIcon,
  ChartBarIcon,
  TicketIcon,
  UserIcon,
  CalendarIcon,
  CheckCircleIcon,
  ArrowLeftIcon,
  InformationCircleIcon,
  PaperClipIcon,
  CloudArrowUpIcon,
  TrashIcon,
  DocumentIcon,
  ExclamationTriangleIcon,
  PlusIcon,
} from "@heroicons/react/24/outline";
// Note: Using string "temporary" instead of ATTACHMENT_OWNERSHIP_TYPE.TEMPORARY
// because AttachmentAPI expects string keys for ATTACHMENT_TYPE_NAMES lookup

function AdminEventContractStep3Page() {
  const navigate = useNavigate();
  const wizardStorage = useEventContractWizardStorage();
  const attachmentManager = useAttachmentManager();

  // State management
  const [attachments, setAttachments] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isUploadingFiles, setIsUploadingFiles] = useState(false);
  const [uploadProgress, setUploadProgress] = useState({});
  const [errors, setErrors] = useState({});
  const [successMessage, setSuccessMessage] = useState("");
  const [isDragOver, setIsDragOver] = useState(false);

  // Generate a valid MongoDB ObjectID for temporary attachments
  const generateObjectId = useCallback(() => {
    // MongoDB ObjectID is a 24-character hex string
    // First 4 bytes: timestamp, next 5 bytes: random, last 3 bytes: counter
    const timestamp = Math.floor(Date.now() / 1000)
      .toString(16)
      .padStart(8, "0");
    const randomBytes = Math.random()
      .toString(16)
      .substring(2, 12)
      .padEnd(10, "0");
    const counter = Math.floor(Math.random() * 0xffffff)
      .toString(16)
      .padStart(6, "0");
    return timestamp + randomBytes + counter;
  }, []);

  // Get list of temporary attachment IDs for this wizard session
  const getTemporaryAttachmentIds = useCallback(() => {
    const attachmentIds =
      wizardStorage.getWizardStep("temporaryAttachmentIds") || [];
    return Array.isArray(attachmentIds) ? attachmentIds : [];
  }, [wizardStorage]);

  // Add a temporary attachment ID to the list
  const addTemporaryAttachmentId = useCallback(
    (attachmentId) => {
      const currentIds = getTemporaryAttachmentIds();

      if (!currentIds.includes(attachmentId)) {
        const updatedIds = [...currentIds, attachmentId];
        wizardStorage.updateWizardStep("temporaryAttachmentIds", updatedIds);
      }
    },
    [wizardStorage, getTemporaryAttachmentIds],
  );

  // Remove a temporary attachment ID from the list
  const removeTemporaryAttachmentId = useCallback(
    (attachmentId) => {
      const currentIds = getTemporaryAttachmentIds();
      const updatedIds = currentIds.filter((id) => id !== attachmentId);
      wizardStorage.updateWizardStep("temporaryAttachmentIds", updatedIds);
    },
    [wizardStorage, getTemporaryAttachmentIds],
  );

  // Clear all temporary attachment IDs (for cleanup after contract creation)
  const clearTemporaryAttachmentIds = useCallback(() => {
    wizardStorage.updateWizardStep("temporaryAttachmentIds", []);
  }, [wizardStorage]);

  // Handle unauthorized access
  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  // Load attachments for this session
  const loadAttachments = useCallback(async () => {
    try {
      setIsLoading(true);
      setErrors({});

      const temporaryAttachmentIds = getTemporaryAttachmentIds();

      // If no temporary attachment IDs are stored, show empty list
      if (temporaryAttachmentIds.length === 0) {
        setAttachments([]);
        return;
      }

      // Get all temporary attachments and then filter by our specific IDs
      const attachmentsData = await attachmentManager.getAttachments(
        {
          ownershipType: "temporary", // Use string key for ATTACHMENT_TYPE_NAMES lookup
          sortBy: "created_at",
          sortOrder: "DESC",
          limit: 1000, // Get more to ensure we capture all our attachments
        },
        onUnauthorized,
        true, // force refresh
      );

      // Filter to only show attachments with IDs that we've stored
      const filteredAttachments = (attachmentsData.results || []).filter(
        (attachment) => temporaryAttachmentIds.includes(attachment.id),
      );

      setAttachments(filteredAttachments);
    } catch (error) {
      if (process.env.NODE_ENV === "development") {
        console.error("Step3Page: Failed to load attachments", error);
      }
      setErrors({
        load: "Failed to load attachments. Please try again.",
      });
    } finally {
      setIsLoading(false);
    }
  }, [attachmentManager, getTemporaryAttachmentIds, onUnauthorized]);

  // Load attachments on component mount
  useEffect(() => {
    loadAttachments();
  }, [loadAttachments]);

  // File upload handler
  const handleFileUpload = useCallback(
    async (files) => {
      if (!files || files.length === 0) return;

      try {
        setIsUploadingFiles(true);
        setErrors({});

        const uploadPromises = Array.from(files).map(async (file, index) => {
          const fileId = `${Date.now()}_${index}`;
          setUploadProgress((prev) => ({ ...prev, [fileId]: 0 }));

          try {
            // Generate a unique temporary ID for this attachment
            const temporaryAttachmentId = generateObjectId();

            const metadata = {
              ownershipType: "temporary", // Use string key for ATTACHMENT_TYPE_NAMES lookup
              ownershipId: temporaryAttachmentId, // Use unique ID for each attachment
              title: file.name,
              description: `Temporary attachment for event contract creation - File: ${file.name}`,
            };

            const uploadedAttachment = await attachmentManager.uploadAttachment(
              file,
              metadata,
              (progress) => {
                setUploadProgress((prev) => ({ ...prev, [fileId]: progress }));
              },
              onUnauthorized,
            );

            setUploadProgress((prev) => {
              const updated = { ...prev };
              delete updated[fileId];
              return updated;
            });

            // Add the temporary attachment ID to our stored list (not the server's attachment ID)
            // The backend will use this temporary ID to find the attachment
            addTemporaryAttachmentId(temporaryAttachmentId);

            return uploadedAttachment;
          } catch (error) {
            setUploadProgress((prev) => {
              const updated = { ...prev };
              delete updated[fileId];
              return updated;
            });
            throw error;
          }
        });

        await Promise.all(uploadPromises);

        // Reload attachments after successful upload
        await loadAttachments();

        setSuccessMessage(`Successfully uploaded ${files.length} file(s)`);
        setTimeout(() => setSuccessMessage(""), 3000);
      } catch (error) {
        if (process.env.NODE_ENV === "development") {
          console.error("Step3Page: File upload failed", error);
        }
        setErrors({
          upload:
            typeof error === "string"
              ? error
              : "Failed to upload files. Please try again.",
        });
      } finally {
        setIsUploadingFiles(false);
        setUploadProgress({});
      }
    },
    [
      attachmentManager,
      onUnauthorized,
      loadAttachments,
      generateObjectId,
      addTemporaryAttachmentId,
    ],
  );

  // File deletion handler
  const handleDeleteAttachment = useCallback(
    async (attachmentId) => {
      if (!window.confirm("Are you sure you want to delete this attachment?")) {
        return;
      }

      try {
        setErrors({});
        await attachmentManager.deleteAttachment(attachmentId, onUnauthorized);

        // Remove from our stored list of temporary attachment IDs
        removeTemporaryAttachmentId(attachmentId);

        // Remove from local state
        setAttachments((prev) => prev.filter((att) => att.id !== attachmentId));

        setSuccessMessage("Attachment deleted successfully");
        setTimeout(() => setSuccessMessage(""), 3000);
      } catch (error) {
        if (process.env.NODE_ENV === "development") {
          console.error("Step3Page: Failed to delete attachment", error);
        }
        setErrors({
          delete: "Failed to delete attachment. Please try again.",
        });
      }
    },
    [
      attachmentManager,
      onUnauthorized,
      removeTemporaryAttachmentId,
      getTemporaryAttachmentIds,
    ],
  );

  // Drag and drop handlers
  const handleDragOver = useCallback((e) => {
    e.preventDefault();
    setIsDragOver(true);
  }, []);

  const handleDragLeave = useCallback((e) => {
    e.preventDefault();
    setIsDragOver(false);
  }, []);

  const handleDrop = useCallback(
    (e) => {
      e.preventDefault();
      setIsDragOver(false);

      const files = e.dataTransfer.files;
      if (files.length > 0) {
        handleFileUpload(files);
      }
    },
    [handleFileUpload],
  );

  // File input change handler
  const handleFileInputChange = useCallback(
    (e) => {
      const files = e.target.files;
      if (files && files.length > 0) {
        handleFileUpload(files);
      }
      // Reset the input so the same file can be uploaded again
      e.target.value = "";
    },
    [handleFileUpload],
  );

  // Handle contract submission
  const handleSubmitContract = useCallback(() => {
    // In a real implementation, you would submit the contract data here.

    // Clear wizard data after submission
    wizardStorage.clearWizardData();

    // Navigate to event contracts list with a success message
    navigate("/admin/event-contracts", {
      state: {
        successMessage:
          "Event contract creation simulated successfully! (Stub implementation)",
      },
    });
  }, [navigate, wizardStorage]);

  // Handle going back to event results
  const handleBackToEventResults = useCallback(() => {
    navigate("/admin/event-contracts/add/step-1-results");
  }, [navigate]);

  // Handle starting over
  const handleStartOver = useCallback(() => {
    // Clear temporary attachment IDs before clearing wizard data
    clearTemporaryAttachmentIds();
    wizardStorage.clearWizardData();
    navigate("/admin/event-contracts/add/step-1-search");
  }, [navigate, wizardStorage, clearTemporaryAttachmentIds]);

  // Format file size for display
  const formatFileSize = useCallback((bytes) => {
    if (bytes === 0) return "0 Bytes";
    const k = 1024;
    const sizes = ["Bytes", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  }, []);

  // Get file type icon
  const getFileTypeIcon = useCallback((fileType) => {
    if (fileType?.startsWith("image/")) {
      return <DocumentIcon className="w-6 h-6 text-green-500" />;
    } else if (fileType === "application/pdf") {
      return <DocumentIcon className="w-6 h-6 text-red-500" />;
    } else if (fileType?.includes("word") || fileType?.includes("document")) {
      return <DocumentIcon className="w-6 h-6 text-blue-500" />;
    } else if (fileType?.includes("sheet") || fileType?.includes("excel")) {
      return <DocumentIcon className="w-6 h-6 text-green-600" />;
    } else {
      return <DocumentIcon className="w-6 h-6 text-gray-500" />;
    }
  }, []);

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Breadcrumb */}
        <nav className="flex mb-8" aria-label="Breadcrumb">
          <ol className="inline-flex items-center space-x-1 md:space-x-3">
            <li className="inline-flex items-center">
              <Link
                to="/admin/dashboard"
                className="inline-flex items-center text-sm font-medium text-gray-700 hover:text-blue-600"
              >
                <ChartBarIcon className="w-4 h-4 mr-2" />
                Dashboard
              </Link>
            </li>
            <li>
              <div className="flex items-center">
                <ChevronRightIcon className="w-5 h-5 text-gray-400" />
                <Link
                  to="/admin/event-contracts"
                  className="ml-1 text-sm font-medium text-gray-700 hover:text-blue-600 md:ml-2"
                >
                  Event Contracts
                </Link>
              </div>
            </li>
            <li aria-current="page">
              <div className="flex items-center">
                <ChevronRightIcon className="w-5 h-5 text-gray-400" />
                <span className="ml-1 text-sm font-medium text-black md:ml-2">
                  Create New Contract
                </span>
              </div>
            </li>
          </ol>
        </nav>

        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-black flex items-center">
            <PaperClipIcon className="w-8 h-8 mr-3 text-blue-600" />
            Create Event Contract - Step 3: Attachments
          </h1>
          <p className="mt-2 text-gray-600">
            Upload any relevant documents or files for this event contract. All
            attachments are temporary and will be associated with the contract
            upon creation.
          </p>
        </div>

        {/* Progress Steps */}
        <div className="mb-8">
          <div className="flex items-center">
            <div className="flex items-center">
              <div className="flex items-center justify-center w-8 h-8 bg-green-600 rounded-full text-white text-sm font-bold">
                <CheckCircleIcon className="w-5 h-5" />
              </div>
              <span className="ml-2 text-sm font-medium text-gray-900">
                Find Event
              </span>
            </div>
            <ChevronRightIcon className="w-5 h-5 text-gray-400 mx-4" />
            <div className="flex items-center">
              <div className="flex items-center justify-center w-8 h-8 bg-green-600 rounded-full text-white text-sm font-bold">
                <CheckCircleIcon className="w-5 h-5" />
              </div>
              <span className="ml-2 text-sm font-medium text-gray-900">
                Contract
              </span>
            </div>
            <ChevronRightIcon className="w-5 h-5 text-gray-400 mx-4" />
            <div className="flex items-center">
              <div className="flex items-center justify-center w-8 h-8 bg-blue-600 rounded-full text-white text-sm font-bold">
                3
              </div>
              <span className="ml-2 text-sm font-medium text-gray-900">
                Attachments
              </span>
            </div>
            <ChevronRightIcon className="w-5 h-5 text-gray-400 mx-4" />
            <div className="flex items-center">
              <div className="flex items-center justify-center w-8 h-8 bg-gray-300 rounded-full text-gray-600 text-sm font-bold">
                4
              </div>
              <span className="ml-2 text-sm font-medium text-gray-500">
                Review & Confirm
              </span>
            </div>
          </div>
        </div>

        {/* Error and Success Messages */}
        {errors.load && (
          <div className="mb-6">
            <Alert variant="error" icon={ExclamationTriangleIcon}>
              {errors.load}
            </Alert>
          </div>
        )}

        {errors.upload && (
          <div className="mb-6">
            <Alert variant="error" icon={ExclamationTriangleIcon}>
              {errors.upload}
            </Alert>
          </div>
        )}

        {errors.delete && (
          <div className="mb-6">
            <Alert variant="error" icon={ExclamationTriangleIcon}>
              {errors.delete}
            </Alert>
          </div>
        )}

        {successMessage && (
          <div className="mb-6">
            <Alert variant="success" icon={CheckCircleIcon}>
              {successMessage}
            </Alert>
          </div>
        )}

        {/* Attachments Section */}
        <div className="space-y-6">
          {/* File Upload Card */}
          <Card>
            <div className="p-6">
              <div className="flex items-center mb-4">
                <CloudArrowUpIcon className="w-6 h-6 text-blue-600 mr-2" />
                <h2 className="text-xl font-semibold text-gray-900">
                  Upload Attachments
                </h2>
              </div>

              {/* File Upload Area */}
              <div
                className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
                  isDragOver
                    ? "border-blue-500 bg-blue-50"
                    : "border-gray-300 hover:border-gray-400"
                } ${isUploadingFiles ? "opacity-50 pointer-events-none" : ""}`}
                onDragOver={handleDragOver}
                onDragLeave={handleDragLeave}
                onDrop={handleDrop}
              >
                <CloudArrowUpIcon className="w-12 h-12 text-gray-400 mx-auto mb-4" />
                <div className="space-y-2">
                  <p className="text-lg font-medium text-gray-900">
                    {isDragOver
                      ? "Drop files here"
                      : "Drag and drop files here"}
                  </p>
                  <p className="text-gray-600">
                    or{" "}
                    <label
                      htmlFor="file-upload"
                      className="text-blue-600 hover:text-blue-700 cursor-pointer font-medium"
                    >
                      browse to upload
                    </label>
                  </p>
                  <p className="text-sm text-gray-500">
                    Supports: PDF, Word, Excel, Images, Text files (max 50MB
                    each)
                  </p>
                </div>

                <input
                  id="file-upload"
                  type="file"
                  multiple
                  className="hidden"
                  onChange={handleFileInputChange}
                  disabled={isUploadingFiles}
                  accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.gif,.webp,.txt,.csv"
                />
              </div>

              {/* Upload Progress */}
              {Object.keys(uploadProgress).length > 0 && (
                <div className="mt-4 space-y-2">
                  <p className="text-sm font-medium text-gray-700">
                    Uploading files...
                  </p>
                  {Object.entries(uploadProgress).map(([fileId, progress]) => (
                    <div
                      key={fileId}
                      className="w-full bg-gray-200 rounded-full h-2"
                    >
                      <div
                        className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                        style={{ width: `${progress}%` }}
                      ></div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </Card>

          {/* Attachments List Card */}
          <Card>
            <div className="p-6">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center">
                  <PaperClipIcon className="w-6 h-6 text-blue-600 mr-2" />
                  <h2 className="text-xl font-semibold text-gray-900">
                    Uploaded Attachments
                  </h2>
                  <span className="ml-2 px-2 py-1 bg-gray-100 text-gray-600 rounded-full text-sm">
                    {attachments.length}
                  </span>
                </div>
              </div>

              {/* Attachments List */}
              {isLoading ? (
                <div className="text-center py-8">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
                  <p className="mt-2 text-gray-600">Loading attachments...</p>
                </div>
              ) : attachments.length === 0 ? (
                <div className="text-center py-8">
                  <DocumentIcon className="w-12 h-12 text-gray-300 mx-auto mb-4" />
                  <p className="text-gray-600">No attachments uploaded yet</p>
                  <p className="text-sm text-gray-500 mt-1">
                    Upload files using the area above
                  </p>
                </div>
              ) : (
                <div className="space-y-3">
                  {attachments.map((attachment) => (
                    <div
                      key={attachment.id}
                      className="flex items-center justify-between p-4 bg-gray-50 rounded-lg border"
                    >
                      <div className="flex items-center space-x-3">
                        {getFileTypeIcon(attachment.fileType)}
                        <div>
                          <p className="font-medium text-gray-900">
                            {attachment.fileName || attachment.title}
                          </p>
                          <div className="flex items-center space-x-4 text-sm text-gray-500">
                            <span>{formatFileSize(attachment.fileSize)}</span>
                            <span>{attachment.fileType}</span>
                            {attachment.createdAt && (
                              <span>Uploaded: {attachment.createdAt}</span>
                            )}
                          </div>
                        </div>
                      </div>

                      <div className="flex items-center space-x-2">
                        <Button
                          variant="danger"
                          size="sm"
                          onClick={() => handleDeleteAttachment(attachment.id)}
                          className="flex items-center"
                        >
                          <TrashIcon className="w-4 h-4 mr-1" />
                          Delete
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </Card>

          {/* Navigation Card */}
          <Card>
            <div className="p-6">
              <div className="flex items-center mb-4">
                <InformationCircleIcon className="w-6 h-6 text-blue-600 mr-2" />
                <h2 className="text-xl font-semibold text-gray-900">
                  Next Steps
                </h2>
              </div>

              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
                <p className="text-sm text-blue-800">
                  When you're finished uploading attachments, proceed to the
                  final step to review and create your event contract.
                </p>
              </div>

              {/* Action Buttons */}
              <div className="flex justify-between">
                <div className="flex gap-3">
                  <Button
                    variant="secondary"
                    onClick={handleBackToEventResults}
                  >
                    <ArrowLeftIcon className="w-4 h-4 mr-1" />
                    Back to Event Selection
                  </Button>
                  <Button variant="secondary" onClick={handleStartOver}>
                    Start Over
                  </Button>
                </div>
                <div className="flex gap-3">
                  <Link to="/admin/event-contracts">
                    <Button variant="secondary">Cancel</Button>
                  </Link>
                  <Button
                    variant="primary"
                    onClick={() =>
                      navigate("/admin/event-contracts/add/step-4")
                    }
                  >
                    Next: Review & Confirm
                    <CheckCircleIcon className="w-4 h-4 ml-1" />
                  </Button>
                </div>
              </div>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

export default AdminEventContractStep3Page;
