'use client';

import { useState, useEffect, type KeyboardEvent } from 'react';
import { Search, FileSearch, Loader2 } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { StatusBadge } from '@/components/status-badge';
import { getCertificates, CertificateItem } from '@/lib/api/compatibility-certifications';
import { DataPagination } from '@/components/ui/data-pagination';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

interface PaginationInfo {
  page: number;
  pageSize: number;
  total: number;
  totalPages: number;
}

export function CertificateVerification() {
  const [searchTerm, setSearchTerm] = useState('');
  const [hasSearched, setHasSearched] = useState(false);
  const [certificateData, setCertificateData] = useState<CertificateItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [pagination, setPagination] = useState<PaginationInfo>({
    page: 1,
    pageSize: 10,
    total: 0,
    totalPages: 0,
  });

  const fetchCertificates = async (
    search: string = '',
    currentPage: number = 1,
    perPage: number = 10
  ) => {
    try {
      setIsLoading(true);
      const response = await getCertificates(search, currentPage, perPage);
      if (response && response.data) {
        setCertificateData(response.data);
        setPagination({
          page: response.cur_page,
          pageSize: response.per_page,
          total: response.total_num,
          totalPages: Math.ceil((response.total_num || 0) / response.per_page),
        });
      }
    } catch (error) {
      console.error('Failed to fetch certificates:', error);
      setCertificateData([]);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchCertificates('', 1, 10);
  }, []);

  const handlePageChange = (page: number) => {
    fetchCertificates(searchTerm, page, pagination.pageSize);
  };

  const handleSearch = () => {
    if (searchTerm.trim()) {
      setHasSearched(true);
      fetchCertificates(searchTerm, 1, pagination.pageSize);
    } else {
      setHasSearched(false);
      fetchCertificates('', 1, pagination.pageSize);
    }
  };

  const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  const formatDateRange = (from: string, to: string) => {
    return `${from} ~ ${to}`;
  };

  return (
    <div className="bg-white p-6 rounded-md">
      <h2 className="text-lg font-semibold mb-4">认证查询</h2>
      <div className="space-y-4">
        <div className='flex items-center gap-2'>
          <div className="relative">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-500" />
            <Input
              placeholder="输入厂商名称或产品名称"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyDown={handleKeyDown}
              className="pl-10 max-w-md"
            />
          </div>
          <Button onClick={handleSearch} disabled={isLoading}>
            {isLoading ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                查询中
              </>
            ) : (
              '查询'
            )}
          </Button>
        </div>
        <div className="relative">
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>互认证编码</TableHead>
                  <TableHead>厂商名称</TableHead>
                  <TableHead>产品名称</TableHead>
                  <TableHead>适配产品</TableHead>
                  <TableHead>适配类型</TableHead>
                  <TableHead className="text-center min-w-[90px]">认证状态</TableHead>
                  <TableHead>证书有效期</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  <TableRow>
                    <TableCell colSpan={7} className="h-32">
                      <div className="flex items-center justify-center">
                        <Loader2 className="h-6 w-6 animate-spin text-blue-600 mr-2" />
                        <span className="text-gray-500">加载中...</span>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : certificateData.length > 0 ? (
                  certificateData.map((item) => (
                    <TableRow key={item.number}>
                      <TableCell className="font-mono text-sm">{item.number}</TableCell>
                      <TableCell>{item.company}</TableCell>
                      <TableCell>{item.product_name}</TableCell>
                      <TableCell>{item.compatible_database_version}</TableCell>
                      <TableCell>{item.solution_type}</TableCell>
                      <TableCell className="text-center">
                        <StatusBadge status={item.status} />
                      </TableCell>
                      <TableCell className="text-sm">
                        {formatDateRange(item.cert_valid_from, item.cert_valid_to)}
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={7} className="h-32">
                      <div className="flex flex-col items-center justify-center text-center">
                        <div className="rounded-full bg-gray-100 p-4 mb-4">
                          <FileSearch className="h-6 w-6 text-gray-400" />
                        </div>
                        {hasSearched ? (
                          <p className="text-gray-500 max-w-lg text-sm">未找到匹配的证书</p>
                        ) : (
                          <p className="text-gray-500 max-w-lg text-sm">暂无认证的证书</p>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>
          {!isLoading && certificateData.length > 0 && pagination.totalPages > 1 && (
            <div className="flex items-center justify-end mt-4">
              <DataPagination
                currentPage={pagination.page}
                totalPages={pagination.totalPages}
                pageSize={pagination.pageSize}
                total={pagination.total}
                onPageChange={handlePageChange}
                disabled={isLoading}
                showSizeChanger={false}
                showTotal={true}
              />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
