import React, { useState, useRef } from "react";
import { Button } from "primereact/button";
import { InputText } from "primereact/inputtext";
import { Dialog } from "primereact/dialog";
import { Calendar } from "primereact/calendar";

const PendingDocumentUpload = ({ pendingDocuments, setPendingDocuments, toast, label = "Documents", remark, documentType }) => {
  const [uploadDialogVisible, setUploadDialogVisible] = useState(false);
  const [selectedFiles, setSelectedFiles] = useState([]);
  const [fileDescriptions, setFileDescriptions] = useState({});
  const [fileDates, setFileDates] = useState({});
  const fileInputRef = useRef(null);

  const handleFileSelect = (event) => {
    const files = event.target.files || [];

    if (files.length > 0) {
      const fileArray = Array.from(files);
      const validFiles = fileArray.filter(file => file.size <= 10 * 1024 * 1024);
      const oversizedFiles = fileArray.filter(file => file.size > 10 * 1024 * 1024);

      if (oversizedFiles.length > 0) {
        toast.current?.show({
          severity: "error",
          summary: "File Size Error",
          detail: `Some files exceed 10MB limit: ${oversizedFiles.map(f => f.name).join(', ')}`,
          life: 5000,
        });
      }

      setSelectedFiles(validFiles);
      setFileDescriptions({});
      setFileDates({});
      setUploadDialogVisible(true);
    }
  };

  const handleRemoveFile = (indexToRemove) => {
    const updatedFiles = selectedFiles.filter((_, index) => index !== indexToRemove);
    const updatedDescriptions = {};
    const updatedDates = {};

    updatedFiles.forEach((file, newIndex) => {
      const oldIndex = selectedFiles.findIndex((f, i) => i < indexToRemove ? i === newIndex : i === newIndex + 1);
      if (oldIndex !== -1) {
        if (fileDescriptions[oldIndex]) {
          updatedDescriptions[newIndex] = fileDescriptions[oldIndex];
        }
        if (fileDates[oldIndex]) {
          updatedDates[newIndex] = fileDates[oldIndex];
        }
      }
    });

    setSelectedFiles(updatedFiles);
    setFileDescriptions(updatedDescriptions);
    setFileDates(updatedDates);
  };

  const handleAddToPending = () => {
    if (!selectedFiles || selectedFiles.length === 0) {
      toast.current?.show({
        severity: "warn",
        summary: "Warning",
        detail: "Please select at least one file",
        life: 3000,
      });
      return;
    }

    const missingDescription = selectedFiles.some((_, index) => {
      const desc = fileDescriptions[index];
      return !desc || desc.trim() === "";
    });

    if (missingDescription) {
      toast.current?.show({
        severity: "warn",
        summary: "Description required",
        detail: "Please enter a description for each document.",
        life: 3000,
      });
      return;
    }

    const missingDate = selectedFiles.some((_, index) => {
      const date = fileDates[index];
      return !date || date.trim() === "";
    });

    if (missingDate) {
      toast.current?.show({
        severity: "warn",
        summary: "Date required",
        detail: "Please select a date for each document.",
        life: 3000,
      });
      return;
    }

    // Add files to pending documents
    const newPendingDocs = selectedFiles.map((file, index) => ({
      file,
      description: fileDescriptions[index] || "",
      date: fileDates[index] || "",
      id: Date.now() + index, // Temporary ID
      ...(documentType != null && { documentType }),
    }));

    setPendingDocuments([...pendingDocuments, ...newPendingDocs]);
    setUploadDialogVisible(false);
    setSelectedFiles([]);
    setFileDescriptions({});
    setFileDates({});
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }

    toast.current?.show({
      severity: "success",
      summary: "Success",
      detail: `${newPendingDocs.length} document(s) added. They will be uploaded when you save the requisition.`,
      life: 3000,
    });
  };

  const handleRemovePending = (indexToRemove) => {
    setPendingDocuments(pendingDocuments.filter((_, index) => index !== indexToRemove));
  };

  const formatFileSize = (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 Math.round(bytes / Math.pow(k, i) * 100) / 100 + " " + sizes[i];
  };

  const getFileIcon = (mimeType) => {
    if (!mimeType) return "pi pi-file";
    if (mimeType.startsWith("image/")) return "pi pi-image";
    if (mimeType.includes("pdf")) return "pi pi-file-pdf";
    if (mimeType.includes("word") || mimeType.includes("document")) return "pi pi-file-word";
    if (mimeType.includes("excel") || mimeType.includes("spreadsheet")) return "pi pi-file-excel";
    return "pi pi-file";
  };

  return (
    <div className="w-full">
      <div className="mb-4">
        <div className="flex items-center justify-between mb-1">
          <label className="block text-base font-semibold text-gray-800 flex items-center gap-2">
            <i className="pi pi-file text-lg text-blue-600"></i>
            {label}
          </label>
          <Button
            type="button"
            icon="pi pi-upload"
            label="Add Documents"
            className="p-button-sm w-fit"
            onClick={() => setUploadDialogVisible(true)}
          />
        </div>
        {remark && (
          <p className="text-sm text-gray-600 mt-1">{remark}</p>
        )}
      </div>

      {pendingDocuments.length === 0 ? (
        <div className="text-center py-12 text-gray-500 border-2 border-dashed border-gray-300 rounded-lg bg-gray-50">
          <div className="w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-3">
            <i className="pi pi-file text-3xl text-gray-400"></i>
          </div>
          <p className="text-sm font-medium text-gray-600 mb-1">No documents added yet</p>
          <p className="text-xs text-gray-500">Click "Add Documents" to add files. They will be uploaded when you save the requisition.</p>
        </div>
      ) : (
        <div className="space-y-2">
          {pendingDocuments.map((doc, index) => {
            const isImage = doc.file.type?.startsWith('image/');
            const imageUrl = isImage ? URL.createObjectURL(doc.file) : null;

            return (
              <div key={doc.id} className="flex items-center justify-between p-4 border border-gray-200 rounded-lg hover:bg-gray-50 bg-white">
                <div className="flex items-center gap-4 flex-1 min-w-0">
                  <div className="flex-shrink-0">
                    {isImage && imageUrl ? (
                      <img src={imageUrl} alt={doc.file.name} className="w-12 h-12 object-cover rounded-lg" />
                    ) : (
                      <div className="w-12 h-12 rounded-lg bg-blue-50 flex items-center justify-center">
                        <i className={`${getFileIcon(doc.file.type)} text-xl text-blue-600`}></i>
                      </div>
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-semibold text-sm text-gray-800 truncate mb-1">{doc.file.name}</div>
                    {doc.description && (
                      <div className="text-xs text-gray-600 truncate mb-1">{doc.description}</div>
                    )}
                    <div className="flex items-center gap-3 flex-wrap text-xs text-gray-500">
                      <span className="flex items-center gap-1">
                        <i className="pi pi-file text-xs"></i>
                        {formatFileSize(doc.file.size)}
                      </span>
                      {doc.date && (
                        <span className="flex items-center gap-1">
                          <i className="pi pi-calendar text-xs"></i>
                          {new Date(doc.date).toLocaleDateString()}
                        </span>
                      )}
                      <span className="px-2 py-1 bg-yellow-100 text-yellow-800 rounded text-xs font-semibold">
                        Pending Upload
                      </span>
                    </div>
                  </div>
                </div>
                <Button
                  type="button"
                  icon="pi pi-trash"
                  className="p-button-rounded p-button-text p-button-danger p-button-sm hover:bg-red-50"
                  onClick={() => {
                    if (imageUrl) URL.revokeObjectURL(imageUrl);
                    handleRemovePending(index);
                  }}
                  tooltip="Remove"
                  tooltipOptions={{ position: "top" }}
                />
              </div>
            );
          })}
        </div>
      )}

      {/* Upload Dialog - Same style as DocumentUpload */}
      <Dialog
        header={
          <div className="flex items-center gap-2">
            <i className="pi pi-upload text-xl"></i>
            <span className="text-lg font-semibold">Add Documents</span>
          </div>
        }
        visible={uploadDialogVisible}
        style={{ width: "600px" }}
        className="p-fluid"
        onHide={() => {
          setUploadDialogVisible(false);
          setSelectedFiles([]);
          setFileDescriptions({});
          setFileDates({});
        }}
        footer={
          <div className="flex justify-end gap-2">
            <Button
              type="button"
              label="Cancel"
              icon="pi pi-times"
              className="p-button-text"
              onClick={() => {
                setUploadDialogVisible(false);
                setSelectedFiles([]);
                setFileDescriptions({});
                setFileDates({});
                if (fileInputRef.current) {
                  fileInputRef.current.value = '';
                }
              }}
            />
            <Button
              type="button"
              label="Add to List"
              icon="pi pi-check"
              onClick={handleAddToPending}
              disabled={!selectedFiles || selectedFiles.length === 0}
            />
          </div>
        }
      >
        <div className="space-y-4">
          <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-400 transition-colors bg-gray-50">
            <input
              ref={fileInputRef}
              type="file"
              multiple
              accept="*/*"
              onChange={handleFileSelect}
              className="hidden"
              id="pending-file-upload-input"
            />
            <label htmlFor="pending-file-upload-input" className="cursor-pointer">
              <div className="flex flex-col items-center gap-3">
                <div className="w-16 h-16 rounded-full bg-blue-100 flex items-center justify-center">
                  <i className="pi pi-cloud-upload text-3xl text-blue-600"></i>
                </div>
                <div>
                  <p className="text-sm font-medium text-gray-700 mb-1">
                    Click to select files or drag and drop
                  </p>
                  <p className="text-xs text-gray-500">
                    Maximum file size: 10MB
                  </p>
                </div>
                <Button
                  type="button"
                  icon="pi pi-folder-open"
                  label="Choose Files"
                  className="p-button-outlined p-button-sm"
                  onClick={(e) => {
                    e.preventDefault();
                    fileInputRef.current?.click();
                  }}
                />
              </div>
            </label>
          </div>

          {selectedFiles && selectedFiles.length > 0 && (
            <div className="space-y-3 max-h-[500px] overflow-y-auto pr-2">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-semibold text-gray-700">
                  Selected Files ({selectedFiles.length})
                </span>
              </div>
              {selectedFiles.map((file, index) => {
                const isImage = file.type.startsWith('image/');
                const imageUrl = isImage ? URL.createObjectURL(file) : null;

                return (
                  <div
                    key={`${file.name}-${index}`}
                    className="border border-gray-200 rounded-lg p-4 bg-white shadow-sm hover:shadow-md transition-shadow relative"
                  >
                    <Button
                      type="button"
                      icon="pi pi-times"
                      className="absolute top-3 right-3 p-button-rounded p-button-text p-button-danger p-button-sm z-10 hover:bg-red-50"
                      onClick={() => {
                        if (imageUrl) URL.revokeObjectURL(imageUrl);
                        handleRemoveFile(index);
                      }}
                      tooltip="Remove file"
                      tooltipOptions={{ position: "top" }}
                    />

                    <div className="flex items-start gap-4 pr-10 mb-3">
                      {isImage && imageUrl ? (
                        <div className="flex-shrink-0">
                          <img
                            src={imageUrl}
                            alt={file.name}
                            className="w-20 h-20 object-cover rounded-lg border-2 border-gray-200 shadow-sm"
                          />
                        </div>
                      ) : (
                        <div className="flex-shrink-0">
                          <div className="w-20 h-20 rounded-lg bg-gradient-to-br from-blue-50 to-blue-100 flex items-center justify-center border-2 border-blue-200">
                            <i className={`${getFileIcon(file.type)} text-3xl text-blue-600`}></i>
                          </div>
                        </div>
                      )}

                      <div className="flex-1 min-w-0">
                        <div className="text-sm font-semibold text-gray-800 truncate mb-1" title={file.name}>
                          {file.name}
                        </div>
                        <div className="flex items-center gap-2 text-xs text-gray-500">
                          <span className="flex items-center gap-1">
                            <i className="pi pi-file text-xs"></i>
                            {formatFileSize(file.size)}
                          </span>
                        </div>
                      </div>
                    </div>

                    <div className="space-y-3 pt-3 border-t border-gray-100">
                      <div>
                        <label className="block text-xs font-semibold text-gray-700 mb-1.5">
                          Description <span className="text-red-500">*</span>
                        </label>
                        <InputText
                          value={fileDescriptions[index] || ""}
                          onChange={(e) =>
                            setFileDescriptions((prev) => ({
                              ...prev,
                              [index]: e.target.value,
                            }))
                          }
                          placeholder="Enter document description"
                          className="w-full"
                          autoFocus={index === 0}
                        />
                      </div>

                      <div>
                        <label className="block text-xs font-semibold text-gray-700 mb-1.5">
                          <i className="pi pi-calendar text-xs mr-1"></i>
                          Date <span className="text-red-500">*</span>
                        </label>
                        <Calendar
                          value={fileDates[index] ? new Date(fileDates[index] + 'T00:00:00') : null}
                          onChange={(e) => {
                            if (e.value && e.value instanceof Date) {
                              const year = e.value.getFullYear();
                              const month = String(e.value.getMonth() + 1).padStart(2, '0');
                              const day = String(e.value.getDate()).padStart(2, '0');
                              const dateValue = `${year}-${month}-${day}`;
                              setFileDates((prev) => ({
                                ...prev,
                                [index]: dateValue,
                              }));
                            } else {
                              setFileDates((prev) => {
                                const updated = { ...prev };
                                delete updated[index];
                                return updated;
                              });
                            }
                          }}
                          dateFormat="yy-mm-dd"
                          showIcon
                          className="w-full"
                          placeholder="Select date"
                        />
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </Dialog>
    </div>
  );
};

export default PendingDocumentUpload;
