"use client";

import { useState, useEffect } from "react";
import ActionButton from "@/src/components/admin/ui/button/ActionButton";
import { DownloadIcon } from "lucide-react";
import ViewRemarkButton from "../components/modals/ViewRemarkModal";
import SiteVisitUploadModal from "@/src/app/admin/(pages)/(application-details)/_common/components/modals/SiteVisitUploadModal";
import { getSiteVisits, downloadSiteVisitPhoto } from "@/src/services/admin/services";

interface SiteVisitPhoto {
  id: number;
  fileName: string;
  filePath: string;
  originalName: string;
}

interface SiteVisitData {
  id: number;
  date: string;
  remark: string;
  addedBy: string;
  createDateTime: string;
  photos: SiteVisitPhoto[];
}

interface SiteVisitStepProps {
  applicationId: string;
}

export default function SiteVisitStep({ applicationId }: SiteVisitStepProps) {
  const [siteVisits, setSiteVisits] = useState<SiteVisitData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadSiteVisits();
  }, [applicationId]);

  const loadSiteVisits = async () => {
    try {
      setLoading(true);
      const response = await getSiteVisits(Number(applicationId));
      const data = response.data?.data || response.data;
      setSiteVisits(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load site visits");
    } finally {
      setLoading(false);
    }
  };

  const handleDownload = async (photoId: number, fileName: string) => {
    try {
      const response = await downloadSiteVisitPhoto(photoId);
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      link.remove();
    } catch (err) {
      console.error("Error downloading photo:", err);
      alert("Failed to download photo");
    }
  };

  if (loading) {
    return (
      <div className="p-6 space-y-6">
        <div className="flex items-center justify-between border-b pb-4">
          <h3 className="text-xl font-bold text-gray-800">Site Visit Details</h3>
        </div>
        <div className="animate-pulse space-y-4">
          {[1, 2, 3].map((i) => (
            <div key={i} className="h-16 bg-gray-200 rounded"></div>
          ))}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-6">
        <p className="text-red-600 text-center">{error}</p>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between border-b pb-4">
        <h3 className="text-xl font-bold text-gray-800">Site Visit Details</h3>
        <SiteVisitUploadModal 
          applicationId={applicationId} 
          onSuccess={loadSiteVisits} 
        />
      </div>

      {siteVisits.length === 0 ? (
        <p className="text-gray-500 text-center py-8">No site visits recorded yet</p>
      ) : (
        <div className="overflow-x-auto bg-white">
          <table className="w-full text-sm border-collapse">
            <thead className="bg-gray-100 text-gray-700">
              <tr>
                <th className="px-4 py-3 border whitespace-nowrap border-gray-300 text-center w-16">
                  Sr No
                </th>
                <th className="px-4 py-3 border border-gray-300 text-left">
                  Date
                </th>
                <th className="px-4 py-3 border border-gray-300 text-center">
                  Files
                </th>
                <th className="px-4 py-3 border border-gray-300 text-left">
                  Added by
                </th>
                <th className="px-4 py-3 border border-gray-300 text-center">
                  Created Date Time
                </th>
                <th className="px-4 py-3 border border-gray-300 text-center">
                  Remark
                </th>
              </tr>
            </thead>

            <tbody>
              {siteVisits.map((visit, index) => (
                <tr key={visit.id} className="hover:bg-gray-50 transition">
                  <td className="px-4 py-3 border border-gray-300 text-center">
                    {index + 1}
                  </td>

                  <td className="px-4 py-3 border border-gray-300">
                    {new Date(visit.date).toLocaleDateString("en-GB")}
                  </td>

                  <td className="px-4 py-3 border border-gray-300">
                    <div className="flex justify-center gap-2 flex-wrap">
                      {visit.photos.length > 0 ? (
                        visit.photos.map((photo) => (
                          <ActionButton
                            key={photo.id}
                            title={`Download ${photo.originalName}`}
                            onClick={() => handleDownload(photo.id, photo.originalName)}
                            className="inline-flex items-center gap-2 px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-medium rounded-lg transition shadow-sm"
                          >
                            <DownloadIcon size={15} />
                          </ActionButton>
                        ))
                      ) : (
                        <span className="text-gray-400 text-xs">No photos</span>
                      )}
                    </div>
                  </td>

                  <td className="px-4 py-3 border border-gray-300">
                    {visit.addedBy}
                  </td>

                  <td className="px-4 py-3 border border-gray-300">
                    {visit.createDateTime}
                  </td>

                  <td className="px-4 py-3 border border-gray-300 text-center">
                    <ViewRemarkButton
                      remarkText={visit.remark}
                      date={new Date(visit.date).toLocaleDateString("en-GB")}
                    />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
