import React from 'react';
import i18n from "@/lib/i18n";

interface BaseListPageProps<T, TCreate = unknown, TUpdate = unknown> {
  entityName: string;
  items: T[];
  isLoading: boolean;
  error: string | null;
  currentPage: number;
  totalCount: number;
  pageSize: number;
  totalPages: number;
  searchTerm: string;
  onPageChange: (page: number) => void;
  onPageSizeChange: (size: number) => void;
  onSearchChange: (term: string) => void;
  columns: {
    key: keyof T | string;
    label: string;
    render?: (item: T) => React.ReactNode;
  }[];
  onEdit?: (item: T) => void;
  onDelete?: (item: T) => void;
  onView?: (item: T) => void;
  onCreate?: () => void;
  searchPlaceholder?: string;
}

export function BaseListPage<
  T extends { id: string },
  TCreate = unknown,
  TUpdate = unknown,
>({
  entityName,
  items,
  isLoading,
  error,
  currentPage,
  totalCount,
  pageSize,
  totalPages,
  searchTerm,
  onPageChange,
  onPageSizeChange,
  onSearchChange,
  columns,
  onEdit,
  onDelete,
  onView,
  onCreate,
  searchPlaceholder = i18n.t('components.ui.BaseListPage.text_search', { entityName }),
}: BaseListPageProps<T, TCreate, TUpdate>) {
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    onSearchChange(e.target.value);
    onPageChange(1);
  };

  const renderCell = (item: T, column: (typeof columns)[0]) => {
    if (column.render) return column.render(item);
    if (typeof column.key === 'string' && column.key.includes('.')) {
      const keys = column.key.split('.');
      let value = item as unknown;
      for (const key of keys) {
        value = value?.[key as keyof typeof value];
        if (value === undefined || value === null) break;
      }
      return value as React.ReactNode;
    }
    return item[column.key as keyof T] as React.ReactNode;
  };

  if (error) {
    return (
      <div className="p-6">
        <div className="bg-red-50 border border-red-200 rounded-lg px-5 py-4">
          <p className="text-sm text-red-800">{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="p-4 md:p-6">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
        <h1 className="text-xl font-bold text-foreground">{i18n.t('components.ui.BaseListPage.text_1')}{entityName}</h1>
        {onCreate && (
          <button
            onClick={onCreate}
            className="bg-primary text-primary-foreground px-4 py-2 rounded-lg text-sm font-semibold hover:bg-primary/90 transition-colors"
          >
            {i18n.t('components.ui.BaseListPage.text_2')}{entityName}
          </button>
        )}
      </div>

      <div className="mb-4 flex flex-col sm:flex-row gap-3">
        <div className="flex-1">
          <input
            type="text"
            placeholder={searchPlaceholder}
            value={searchTerm}
            onChange={handleSearch}
            className="w-full px-4 py-2 text-sm border border-border rounded-lg bg-background text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>
        <select
          value={pageSize}
          onChange={(e) => onPageSizeChange(Number(e.target.value))}
          className="border border-border rounded-lg px-3 py-2 text-sm bg-background text-foreground cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary"
        >
          <option value={10}>{i18n.t('components.ui.BaseListPage.text_3')}</option>
          <option value={20}>{i18n.t('components.ui.BaseListPage.text_4')}</option>
          <option value={50}>{i18n.t('components.ui.BaseListPage.text_5')}</option>
          <option value={100}>{i18n.t('components.ui.BaseListPage.text_6')}</option>
        </select>
      </div>

      <div className="bg-card border border-border rounded-lg overflow-hidden">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-border">
            <thead className="bg-muted/50">
              <tr>
                {columns.map((column) => (
                  <th key={column.key as string} className="px-4 py-3 text-right text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                    {column.label}
                  </th>
                ))}
                {(onEdit || onDelete || onView) && (
                  <th className="px-4 py-3 text-right text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                    {i18n.t('components.ui.BaseListPage.text_7')}</th>
                )}
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {isLoading ? (
                <tr>
                  <td colSpan={columns.length + 1} className="px-4 py-8 text-center">
                    <div className="flex justify-center">
                      <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                    </div>
                  </td>
                </tr>
              ) : items.length === 0 ? (
                <tr>
                  <td colSpan={columns.length + 1} className="px-4 py-10 text-center text-muted-foreground text-sm">
                    {i18n.t('components.ui.BaseListPage.text_8')}{entityName}
                  </td>
                </tr>
              ) : (
                items.map((item) => (
                  <tr key={item.id} className="hover:bg-muted/30 transition-colors">
                    {columns.map((column) => (
                      <td key={column.key as string} className="px-4 py-3 whitespace-nowrap text-sm text-foreground">
                        {renderCell(item, column)}
                      </td>
                    ))}
                    {(onEdit || onDelete || onView) && (
                      <td className="px-4 py-3 whitespace-nowrap text-sm font-medium space-x-3 space-x-reverse">
                        {onView && (
                          <button onClick={() => onView(item)} className="text-primary hover:text-primary/80 transition-colors">
                            {i18n.t('components.ui.BaseListPage.text_9')}</button>
                        )}
                        {onEdit && (
                          <button onClick={() => onEdit(item)} className="text-primary hover:text-primary/80 transition-colors">
                            {i18n.t('components.ui.BaseListPage.text_10')}</button>
                        )}
                        {onDelete && (
                          <button onClick={() => onDelete(item)} className="text-destructive hover:text-destructive/80 transition-colors">
                            {i18n.t('components.ui.BaseListPage.text_11')}</button>
                        )}
                      </td>
                    )}
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {totalPages > 1 && (
        <div className="mt-5 flex items-center justify-between">
          <div className="text-xs text-muted-foreground">
            {i18n.t('components.ui.BaseListPage.text_12')}{(currentPage - 1) * pageSize + 1} {i18n.t('components.ui.BaseListPage.text_13')}{Math.min(currentPage * pageSize, totalCount)} {i18n.t('components.ui.BaseListPage.text_14')}{totalCount} {i18n.t('components.ui.BaseListPage.text_15')}</div>
          <div className="flex gap-2">
            <button
              onClick={() => onPageChange(Math.max(1, currentPage - 1))}
              disabled={currentPage === 1}
              className="px-3 py-1.5 border border-border rounded-lg text-xs text-foreground disabled:opacity-30 disabled:cursor-not-allowed hover:bg-muted transition-colors"
            >
              {i18n.t('components.ui.BaseListPage.text_16')}</button>
            {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
              const pageNum = Math.max(1, currentPage - 2) + i;
              if (pageNum > totalPages) return null;
              return (
                <button
                  key={pageNum}
                  onClick={() => onPageChange(pageNum)}
                  className={`px-3 py-1.5 text-xs rounded-lg transition-all ${
                    currentPage === pageNum
                      ? 'bg-primary text-primary-foreground font-bold'
                      : 'border border-border text-foreground hover:bg-muted'
                  }`}
                >
                  {pageNum}
                </button>
              );
            })}
            <button
              onClick={() => onPageChange(Math.min(totalPages, currentPage + 1))}
              disabled={currentPage === totalPages}
              className="px-3 py-1.5 border border-border rounded-lg text-xs text-foreground disabled:opacity-30 disabled:cursor-not-allowed hover:bg-muted transition-colors"
            >
              {i18n.t('components.ui.BaseListPage.text_17')}</button>
          </div>
        </div>
      )}
    </div>
  );
}