"use client";

import React, { useEffect, useState } from "react";
import QuotationCard from "./QuotationCard";
import { getQuotationsByApplication, downloadQuotation } from "@/src/services/admin/services";
import { useCustomToast } from "@/src/hooks/web/useCustomToast";

interface UploadedQuotationsListProps {
  applicationId: number;
  onCountChange?: (count: number) => void;
}

export default function UploadedQuotationsList({ applicationId, onCountChange }: UploadedQuotationsListProps) {
  const [quotations, setQuotations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const { showToast } = useCustomToast();

  useEffect(() => {
    fetchQuotations();
  }, [applicationId]);

  const fetchQuotations = async () => {
    try {
      const response = await getQuotationsByApplication(applicationId);
      const data = response.data?.data || response.data || [];
      setQuotations(data);
      if (onCountChange) {
        onCountChange(data.length);
      }
    } catch (error: any) {
      console.error("Error fetching quotations:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleDownload = async (id: string) => {
    try {
      const quotation = quotations.find(q => q.id.toString() === id);
      const response = await downloadQuotation(parseInt(id));
      
      // Use original_name from quotation data
      const filename = quotation?.original_name || `quotation-${id}`;
      
      const url = window.URL.createObjectURL(response.data);
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", filename);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
      showToast({
        title: "Success!",
        description: "Quotation downloaded successfully.",
        type: "success",
      });
    } catch (error: any) {
      showToast({
        title: "Error",
        description: error.response?.data?.message || "Failed to download quotation.",
        type: "error",
      });
    }
  };

  const formatFileSize = (bytes: number) => {
    return (bytes / 1024).toFixed(1) + " KB";
  };

  if (loading) {
    return (
      <div className="flex justify-center py-8">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-600"></div>
      </div>
    );
  }

  if (quotations.length === 0) {
    return null;
  }

  return (
    <div className="space-y-6">
      <div className="border-b pb-4">
        <h3 className="text-xl font-bold text-gray-800">Uploaded Quotations</h3>
        <p className="text-sm text-gray-500 mt-1">
          {quotations.length} quotation{quotations.length !== 1 ? "s" : ""} uploaded
        </p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {quotations.map((quotation) => (
          <QuotationCard
            key={quotation.id}
            id={quotation.id.toString()}
            name={quotation.original_name}
            size={formatFileSize(quotation.file_size)}
            status={quotation.status}
            onDownload={handleDownload}
            showRemove={false}
          />
        ))}
      </div>
    </div>
  );
}
