"use client";

import { useMemo, useCallback, useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { PageHeader } from "@/components/ui/PageHeader";
import { BREADCRUMBS } from "@/constants/breadcrumbs";
import { apiGet } from "@/utils/api-client";
import type { OcrDocumentListItem } from "@/types/ocr";
import { Eye, Plus, RefreshCw, FileText } from "lucide-react";

export default function OcrDocumentsPage() {
  const router = useRouter();
  const [data, setData] = useState<OcrDocumentListItem[]>([]);
  const [loading, setLoading] = useState(true);

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const response = await apiGet<{
        success?: boolean;
        documents?: OcrDocumentListItem[];
        data?: OcrDocumentListItem[];
      }>("/api/ocr/documents");
      const documents = response.documents || response.data || [];
      setData(Array.isArray(documents) ? documents : []);
    } catch (error) {
      console.error("Failed to load OCR documents:", error);
      setData([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadData();
  }, [loadData]);

  const handleView = useCallback(
    (id: number) => {
      router.push(`/ocr/${id}`);
    },
    [router]
  );

  const handleNewWorkflow = useCallback(() => {
    router.push("/ocr/workflow");
  }, [router]);

  const actions = useMemo(
    () => (
      <div className="flex items-center gap-2">
        <button
          onClick={loadData}
          className="inline-flex items-center gap-1.5 px-3 py-2 text-xs font-medium border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition-colors"
        >
          <RefreshCw className="h-3.5 w-3.5" />
          Refresh
        </button>
        <button
          onClick={handleNewWorkflow}
          className="inline-flex items-center gap-1.5 px-3 py-2 text-xs font-medium bg-[#428B4D] text-white rounded-md hover:bg-[#357a3f] transition-colors"
        >
          <Plus className="h-3.5 w-3.5" />
          New Workflow
        </button>
      </div>
    ),
    [loadData, handleNewWorkflow]
  );

  return (
    <div className="container mx-auto px-4 py-10">
      <PageHeader
        title="OCR Documents"
        breadcrumbs={[...BREADCRUMBS.ocrDocuments]}
        actions={actions}
      />

      <div className="mt-6">
        <div className="bg-white rounded-lg shadow-sm border overflow-hidden">
          {loading ? (
            <div className="flex items-center justify-center py-16">
              <div className="text-sm text-gray-400">Loading documents...</div>
            </div>
          ) : data.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 gap-3">
              <FileText className="h-10 w-10 text-gray-300" />
              <div className="text-sm text-gray-400">No OCR documents found.</div>
              <button
                onClick={handleNewWorkflow}
                className="mt-2 inline-flex items-center gap-1.5 px-4 py-2 text-xs font-medium bg-[#428B4D] text-white rounded-md hover:bg-[#357a3f] transition-colors"
              >
                <Plus className="h-3.5 w-3.5" />
                Start New Workflow
              </button>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="bg-gray-50 border-b">
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                      ID
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                      Filename
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                      Bank Type
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                      Document Type
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                      Extraction Date
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                      Positions
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                      Created At
                    </th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {data.map((doc) => (
                    <tr
                      key={doc.ocr_data_id}
                      className="border-b hover:bg-gray-50 transition-colors"
                    >
                      <td className="px-4 py-3 text-xs text-gray-600">
                        {doc.ocr_data_id}
                      </td>
                      <td className="px-4 py-3 text-xs text-gray-800 font-medium max-w-[200px] truncate">
                        {doc.filename}
                      </td>
                      <td className="px-4 py-3">
                        <span className="inline-block px-2 py-0.5 rounded text-[10px] font-medium bg-blue-100 text-blue-800 uppercase">
                          {doc.bank_type || "-"}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-xs text-gray-600">
                        {doc.document_type || "-"}
                      </td>
                      <td className="px-4 py-3 text-xs text-gray-600">
                        {doc.extraction_date || "-"}
                      </td>
                      <td className="px-4 py-3 text-xs text-gray-600">
                        {doc.total_positions ?? "-"}
                      </td>
                      <td className="px-4 py-3 text-xs text-gray-600">
                        {doc.created_at || "-"}
                      </td>
                      <td className="px-4 py-3 text-center">
                        <button
                          onClick={() => handleView(doc.ocr_data_id)}
                          className="inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-medium border rounded hover:bg-gray-50 text-gray-600 transition-colors"
                        >
                          <Eye className="h-3 w-3" />
                          View
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
