"use client";

import { useEffect, useState } from "react";
import SectionWrapper from "@/components/ui/section/SectionWrapper";
import Button from "@/components/ui/buttons/Button";
import {
  Plus,
  FileText,
  Download,
  Share2,
  Upload,
  MoreVertical,
  X,
  ShoppingCart,
} from "lucide-react";
import { DUMMY_DOCUMENTS } from "@/data/client-master";
import { getStatusStyles } from "@/utils/status.utils";

import { ExpiryStatus } from "@/types";
import Loader from "@/components/ui/Loader/Loader";

type UploadedDoc = {
  id: string;
  title: string;
  fileName: string;
  uploadedBy: string;
  uploadDate: string;
  fileSize: string;
  fileType: string;
};

export default function Document({ clientId }: { clientId: string; }) {
  const [loading, setLoading] = useState(true);
  const [isDragActive, setIsDragActive] = useState(false);
  const [documents, setDocuments] = useState(DUMMY_DOCUMENTS);
  const [showNameModal, setShowNameModal] = useState(false);
  const [pendingFile, setPendingFile] = useState<File | null>(null);
  const [documentTitle, setDocumentTitle] = useState("");

  // Get client name from props (you can also fetch it if needed)
  const currentClientName = "Unknown_Client"; // Replace with actual client name if available

  const handleDrag = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
  };

  const handleDragIn = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.dataTransfer.items?.length) setIsDragActive(true);
  };

  const handleDragOut = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragActive(false);
  };

  const generateFileName = (title: string, file: File): string => {
    const now = new Date();
    const mm = String(now.getMonth() + 1).padStart(2, "0");
    const hh = String(now.getHours()).padStart(2, "0");
    const dd = String(now.getDate()).padStart(2, "0");
    const yyyy = now.getFullYear();
    
    // Format: DocumentName_ClientName_MMHHDDMMYYYY
    const cleanTitle = title.replace(/[^a-zA-Z0-9]/g, "_");
    return `${cleanTitle}_${currentClientName.replace(/[^a-zA-Z0-9]/g, "_")}_${mm}${hh}${dd}${mm}${yyyy}`;
  };

  const processDroppedFile = (file: File) => {
    setPendingFile(file);
    setDocumentTitle(file.name.split(".").slice(0, -1).join("."));
    setShowNameModal(true);
  };

  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragActive(false);

    const files = Array.from(e.dataTransfer.files);
    if (files.length > 0) {
      processDroppedFile(files[0]); // Handle first file for now (you can extend to multiple)
    }
  };

  const handleConfirmName = () => {
    if (!pendingFile || !documentTitle.trim()) return;

    const generatedFileName = generateFileName(documentTitle, pendingFile);
    const extension = pendingFile.name.split(".").pop()?.toUpperCase() || "PDF";

    const newDoc: UploadedDoc = {
      id: Date.now().toString(),
      title: documentTitle.trim(),
      fileName: `${generatedFileName}.${extension.toLowerCase()}`,
      uploadedBy: "Current User", // You can make this dynamic
      uploadDate: new Intl.DateTimeFormat("en-GB", {
        day: "2-digit",
        month: "short",
        year: "numeric",
      }).format(new Date()),
      fileSize: `${(pendingFile.size / 1024).toFixed(0)} KB`,
      fileType: extension,
    };

    // setDocuments((prev) => [newDoc, ...prev]);
    setShowNameModal(false);
    setPendingFile(null);
    setDocumentTitle("");
  };

  useEffect(() => {
    const timer = setTimeout(() => setLoading(false), 500);
    return () => clearTimeout(timer);
  }, []);

  return (
    <div className="flex-1 overflow-auto px-6 py-5">
      <SectionWrapper
        title="Documents"
        count={documents}
        countLabel="document"
        countLabelPlural="documents"
        button={
          <Button
            name="Upload Document"
            variant="outline"
            size="sm"
            icon={Plus}
            onClick={() => console.log("Upload clicked")}
          />
        }
      >
        {/* Drag & Drop Area */}
        <div
          onDragOver={handleDrag}
          onDragEnter={handleDragIn}
          onDragLeave={handleDragOut}
          onDrop={handleDrop}
          className={`border-2 border-dashed rounded-lg p-12 text-center mb-8 transition-colors cursor-pointer ${
            isDragActive
              ? "border-blue-500 bg-blue-50"
              : "border-gray-300 bg-gray-50 hover:border-gray-400"
          }`}
        >
          <Upload className={`w-10 h-10 mx-auto mb-4 ${isDragActive ? "text-blue-600" : "text-gray-400"}`} />
          <p className={`text-base font-medium ${isDragActive ? "text-blue-600" : "text-gray-700"}`}>
            Drag & drop files here, or click to browse
          </p>
          <p className="text-sm text-gray-500 mt-1">
            PDF, JPG, PNG, XLSX — max 50 MB per file
          </p>
        </div>

        {/* Documents Grid */}
        {loading ? (
          <Loader />
        ) : (
          <div className="grid grid-cols-3 gap-6">
            {documents.map((doc) => {
              let expiryStatus: ExpiryStatus | null = null;
              if (doc.status === "VALID") expiryStatus = "Valid";
              else if (doc.status === "< 90 DAYS") expiryStatus = "Expiring Soon";
              else if (doc.status === "EXPIRED") expiryStatus = "Expired";

              const statusStyle = getStatusStyles(expiryStatus);

              return (
                <div
                  key={doc.id}
                  className="border border-gray-200 rounded-lg bg-white p-4 hover:shadow-md transition-shadow"
                >
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-start gap-3 flex-1 min-w-0">
                      <FileText className="w-5 h-5 text-gray-600 flex-shrink-0 mt-0.5" />
                      <div className="min-w-0 flex-1">
                        <h3 className="text-sm font-semibold text-gray-900 truncate">
                          {doc.title}
                        </h3>
                        <p className="text-xs text-gray-500 truncate mt-0.5">
                          {doc.fileName}
                        </p>
                      </div>
                    </div>

                    {statusStyle && (
                      <span
                        className={`flex-shrink-0 text-[10px] font-bold uppercase tracking-widest px-2 py-1 rounded ${statusStyle.bg} ${statusStyle.text}`}
                      >
                        {statusStyle.label}
                      </span>
                    )}
                  </div>

                  <div className="mb-4 space-y-1.5 text-xs text-gray-600">
                    <div>
                      <span className="font-medium text-gray-700">{doc.uploadedBy}</span>
                      <span className="text-gray-400"> · {doc.uploadDate}</span>
                    </div>
                  </div>

                  <div className="flex items-center justify-between pt-3 border-t border-gray-100">
                    <span className="text-xs font-medium text-gray-600">{doc.fileSize}</span>

                    <div className="flex items-center gap-1">
                      <button onClick={() => console.log("Download", doc.id)} className="p-1.5 rounded hover:bg-gray-100 text-gray-500 hover:text-gray-700">
                        <ShoppingCart className="w-4 h-4" />
                      </button>
                      <button onClick={() => console.log("Share", doc.id)} className="p-1.5 rounded hover:bg-gray-100 text-gray-500 hover:text-gray-700">
                        <Share2 className="w-4 h-4" />
                      </button>
                      <button onClick={() => console.log("More", doc.id)} className="p-1.5 rounded hover:bg-gray-100 text-gray-500 hover:text-gray-700">
                        <MoreVertical className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </SectionWrapper>

      {/* Document Name Modal */}
      {showNameModal && pendingFile && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 w-full max-w-md mx-4">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-semibold">Name Your Document</h3>
              <button onClick={() => setShowNameModal(false)} className="text-gray-400 hover:text-gray-600">
                <X className="w-5 h-5" />
              </button>
            </div>

            <input
              type="text"
              value={documentTitle}
              onChange={(e) => setDocumentTitle(e.target.value)}
              className="w-full border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:border-blue-500 mb-4"
              placeholder="Enter document name"
              autoFocus
            />

            <div className="bg-gray-50 p-3 rounded-lg text-sm mb-6">
              <p className="text-gray-600 mb-1">Generated Filename:</p>
              <p className="font-mono text-xs break-all text-gray-700">
                {generateFileName(documentTitle || "Untitled", pendingFile)}.
                {pendingFile.name.split(".").pop()?.toLowerCase()}
              </p>
            </div>

            <div className="flex gap-3">
              <Button
                name="Cancel"
                variant="outline"
                onClick={() => setShowNameModal(false)}
                className="flex-1"
              />
              <Button
                name="Save Document"
                onClick={handleConfirmName}
                disabled={!documentTitle.trim()}
                className="flex-1"
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}