"use client";

import { useState, useEffect } from "react";
import TabPanelHeader from "../tab-components/TabPanelHeader";
import QuotationList from "../components/contract-quotation/QuotationList";
import SubmitButton from "../components/contract-quotation/SubmitButton";
import { getQuotationsByApplication, downloadQuotation, updateQuotationStatus } from "@/src/services/admin/services";
import { toast } from "react-hot-toast";

interface Quotation {
  id: number;
  name: string;
  file: string;
  status: string;
  remark?: string;
}

interface ContractQuotationStepProps {
  applicationId: number;
}

export default function ContractQuotationStep({ applicationId }: ContractQuotationStepProps) {
  const [quotations, setQuotations] = useState<Quotation[]>([]);
  const [selectedQuotation, setSelectedQuotation] = useState<number | null>(null);
  const [remark, setRemark] = useState("");
  const [loading, setLoading] = useState(false);
  const [fetchLoading, setFetchLoading] = useState(true);
  const [isEditing, setIsEditing] = useState(false);

  useEffect(() => {
    fetchQuotations();
  }, [applicationId]);

  const fetchQuotations = async () => {
    setFetchLoading(true);
    try {
      const response = await getQuotationsByApplication(applicationId);
      const data = response.data?.data || response.data || [];
      
      const formattedQuotations = data.map((q: any) => ({
        id: q.id,
        name: q.original_name,
        file: q.file_path,
        status: q.status,
        remark: q.remark || "",
      }));
      
      setQuotations(formattedQuotations);
      
      const approvedQuotation = formattedQuotations.find((q: Quotation) => q.status === "Approved");
      if (approvedQuotation) {
        setSelectedQuotation(approvedQuotation.id);
        setRemark(approvedQuotation.remark || "");
      }
    } catch (error: any) {
      toast.error("Failed to fetch quotations");
      console.error("Error fetching quotations:", error);
    } finally {
      setFetchLoading(false);
    }
  };

  const handleSelect = (id: number) => {
    setSelectedQuotation(id);
    const selected = quotations.find(q => q.id === id);
    setRemark(selected?.remark || "");
  };

  const handleDownload = async (file: string) => {
    try {
      const quotation = quotations.find(q => q.file === file);
      if (!quotation) return;
      
      const response = await downloadQuotation(quotation.id);
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", quotation.name);
      document.body.appendChild(link);
      link.click();
      link.remove();
      toast.success("Download started");
    } catch (error: any) {
      toast.error("Failed to download quotation");
    }
  };

  const handleSubmit = async () => {
    if (selectedQuotation === null) return;

    setLoading(true);
    try {
      await updateQuotationStatus(selectedQuotation, "Approved", remark);
      toast.success("Quotation approved successfully!");
      setIsEditing(false);
      fetchQuotations();
    } catch (error: any) {
      toast.error(error.response?.data?.message || "Failed to approve quotation");
    } finally {
      setLoading(false);
    }
  };

  const handleChangeApproval = () => {
    setIsEditing(true);
    const approvedQuotation = quotations.find(q => q.status === "Approved");
    if (approvedQuotation) {
      setSelectedQuotation(approvedQuotation.id);
      setRemark(approvedQuotation.remark || "");
    }
  };

  const approvedQuotation = quotations.find(q => q.status === "Approved");
  const hasApprovedQuotation = !!approvedQuotation && !isEditing;

  if (fetchLoading) {
    return (
      <div className="p-6 min-h-[260px] flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-600"></div>
      </div>
    );
  }

  return (
    <div className="p-6 min-h-[260px] space-y-6">
      <div className="flex items-center justify-between">
        <TabPanelHeader title="Contractor Quotation" />
        {hasApprovedQuotation && (
          <button
            type="button"
            onClick={handleChangeApproval}
            className="bg-orange-500 hover:bg-orange-600 text-white px-4 py-2 rounded-lg text-sm font-medium transition"
          >
            Change Approval
          </button>
        )}
      </div>

      <QuotationList
        quotations={quotations}
        selectedQuotation={selectedQuotation}
        remark={remark}
        onSelect={handleSelect}
        onRemarkChange={setRemark}
        onDownload={handleDownload}
      />

      {(!hasApprovedQuotation || isEditing) && (
        <SubmitButton
          disabled={selectedQuotation === null}
          onClick={handleSubmit}
          loading={loading}
        />
      )}
    </div>
  );
}
