"use client";

import React, { useState, useEffect } from "react";
import { getAgreementDocuments } from "@/src/services/web/services";

interface AgreementDocument {
  id: number;
  file_name: string;
  original_name: string;
  file_size: number;
}

interface AgreementDocumentProps {
  applicationId: string;
}

export default function AgreementDocument({ applicationId }: AgreementDocumentProps) {
  const [documents, setDocuments] = useState<AgreementDocument[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>("");

  useEffect(() => {
    fetchAgreementDocuments();
  }, [applicationId]);

  const fetchAgreementDocuments = async () => {
    try {
      const response = await getAgreementDocuments(applicationId);
      if (response.data.success) {
        setDocuments(response.data.data);
      }
    } catch (error: any) {
      console.error("Error fetching agreement documents:", error);
      if (error?.response?.status === 403) {
        setError("Access denied. You can only view your own documents.");
      } else if (error?.response?.status === 401) {
        setError("Unauthorized. Please log in again.");
      }
    } finally {
      setLoading(false);
    }
  };

  const handleDownload = (id: number) => {
    window.open(
      `${process.env.NEXT_PUBLIC_EXPRESS_BACKEND_URL}/web/documents/download/agreement/${id}`,
      "_blank"
    );
  };

  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return bytes + " B";
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + " KB";
    return (bytes / (1024 * 1024)).toFixed(2) + " MB";
  };

  if (loading) {
    return (
      <div className="flex justify-center py-8">
        <div className="text-gray-500">Loading agreement documents...</div>
      </div>
    );
  }

  return (
    <div className="space-y-8 bg-white rounded-xl relative">
      <div className="space-y-6">
        <div className="flex items-center justify-between border-b pb-4">
          <h3 className="text-xl font-bold text-gray-800">Agreement Document</h3>
        </div>

        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4">
            <p className="text-sm text-red-600">{error}</p>
          </div>
        )}

        {documents.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {documents.map((doc) => (
              <div
                key={doc.id}
                className="relative group border border-gray-200 rounded-xl p-4 bg-gray-50 hover:bg-white hover:border-teal-500 hover:shadow-md transition-all"
              >
                <div className="flex items-start gap-3">
                  <div className="bg-teal-100 p-3 rounded-lg text-teal-700">
                    <svg width="24" height="24" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" />
                    </svg>
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-bold text-gray-800 truncate" title={doc.original_name}>
                      {doc.original_name}
                    </p>
                    <div className="mt-1 flex items-center justify-between gap-2">
                      <p className="text-xs text-gray-500">{formatFileSize(doc.file_size)}</p>
                      <button
                        onClick={() => handleDownload(doc.id)}
                        className="text-[11px] px-2 py-[2px] rounded-md border border-teal-500 text-teal-600 hover:bg-teal-50 hover:text-teal-700 transition-all"
                      >
                        Download
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="border-2 border-dashed border-gray-200 rounded-xl py-10 text-center bg-gray-50/30">
            <p className="text-gray-400 italic">
              No agreement documents available yet.
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
