"use client";

import React, { useState, useMemo } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableHeader,
  TableRow,
} from "../ui/table";
import Badge from "../ui/badge/Badge";
import Button from "../ui/button/Button";
import InputField from "../form/input/InputField";
import { useTranslations } from "next-intl";

interface CaCertificate {
  uuid: string;
  ca_type: string;
  common_name: string;
  serial_number: string;
  valid_from: string;
  valid_to: string;
  status: string;
  is_latest: boolean;
  issuer_name?: string;
  issuer_serial?: string;
}

interface ArchiveManagementTableProps {
  certificates: CaCertificate[];
  onPromote: (uuid: string) => void;
  isPromoting: boolean;
}

export default function ArchiveManagementTable({
  certificates,
  onPromote,
  isPromoting,
}: ArchiveManagementTableProps) {
  const t = useTranslations("RootCA");
  const [searchTerm, setSearchTerm] = useState("");

  const formatType = (type: string) => {
    return type.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
  };

  const filteredCertificates = useMemo(() => {
    return certificates.filter((cert) => {
      const search = searchTerm.toLowerCase();
      return (
        cert.common_name.toLowerCase().includes(search) ||
        cert.ca_type.toLowerCase().includes(search) ||
        cert.serial_number.toLowerCase().includes(search) ||
        cert.uuid.toLowerCase().includes(search)
      );
    });
  }, [certificates, searchTerm]);

  return (
    <div className="space-y-4">
      {/* Table Header Controls */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between px-1">
        <h4 className="text-sm font-bold text-gray-800 dark:text-white/90">CDN Archive History</h4>
        <div className="w-full sm:w-64">
          <InputField
            placeholder="Search version/CN..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="!py-2"
          />
        </div>
      </div>

      <div className="overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-white/[0.05] dark:bg-white/[0.03]">
        <div className="max-w-full overflow-x-auto">
          <Table>
            <TableHeader className="border-b border-gray-100 dark:border-white/[0.05]">
              <TableRow>
                <TableCell isHeader className="px-5 py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400">
                  Version (UUID)
                </TableCell>
                <TableCell isHeader className="px-5 py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400">
                  {t("common_name_th")}
                </TableCell>
                <TableCell isHeader className="px-5 py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400">
                  {t("issuer_th")}
                </TableCell>
                <TableCell isHeader className="px-5 py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400">
                  {t("validity_th")}
                </TableCell>
                <TableCell isHeader className="px-5 py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400">
                  Status
                </TableCell>
                <TableCell isHeader className="px-5 py-3 font-medium text-gray-500 text-center text-theme-xs dark:text-gray-400">
                  {t("actions_th")}
                </TableCell>
              </TableRow>
            </TableHeader>

            <TableBody className="divide-y divide-gray-100 dark:divide-white/[0.05]">
              {filteredCertificates.map((cert) => (
                <TableRow key={cert.uuid} className={`hover:bg-gray-50 dark:hover:bg-white/[0.02] transition-colors ${cert.is_latest ? 'bg-blue-50/30 dark:bg-blue-900/10' : ''}`}>
                  <TableCell className="px-5 py-4 text-start font-mono text-theme-xs text-gray-500 dark:text-gray-400">
                    {cert.uuid}
                  </TableCell>
                  <TableCell className="px-5 py-4 text-start text-theme-sm text-gray-600 dark:text-gray-400">
                    <div className="flex flex-col">
                        <span className="font-medium text-gray-800 dark:text-white/90">{cert.common_name}</span>
                        <span className="text-[10px] text-gray-400">{formatType(cert.ca_type)}</span>
                    </div>
                  </TableCell>
                  <TableCell className="px-5 py-4 text-start">
                    <div className="flex flex-col">
                      <span className="text-[10px] text-gray-700 dark:text-gray-300 font-medium">
                        {cert.issuer_name || "-"}
                      </span>
                      {cert.issuer_serial && (
                        <span className="text-[9px] text-gray-400 font-mono italic leading-tight">
                          {cert.issuer_serial}
                        </span>
                      )}
                    </div>
                  </TableCell>
                  <TableCell className="px-5 py-4 text-start text-theme-xs text-gray-500 dark:text-gray-400">
                    <div className="flex flex-col">
                      <span>{new Date(cert.valid_from).toLocaleDateString()}</span>
                      <span className="text-gray-400 text-[10px]">{t("validity_to_label")}</span>
                      <span>{new Date(cert.valid_to).toLocaleDateString()}</span>
                    </div>
                  </TableCell>
                  <TableCell className="px-5 py-4 text-start">
                    <div className="flex flex-col gap-1">
                        <Badge size="sm" color={cert.status === "valid" ? "success" : "error"}>
                          {cert.status === "valid" ? t("status_valid") : t("status_expired")}
                        </Badge>
                        {cert.is_latest && (
                            <Badge size="sm" color="info">LIVE - LATEST</Badge>
                        )}
                    </div>
                  </TableCell>
                  <TableCell className="px-5 py-4 text-center">
                    {!cert.is_latest && (
                        <Button 
                            size="sm" 
                            variant="outline"
                            onClick={() => onPromote(cert.uuid)} 
                            loading={isPromoting}
                        >
                            Set as Latest
                        </Button>
                    )}
                    {cert.is_latest && (
                         <span className="text-[10px] text-gray-400 font-medium">Currently Public</span>
                    )}
                  </TableCell>
                </TableRow>
              ))}
              {filteredCertificates.length === 0 && (
                <TableRow>
                  <TableCell colSpan={6} className="px-5 py-10 text-center text-gray-500 dark:text-gray-400">
                    No versions found.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      </div>
    </div>
  );
}
