import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/common/ui/table";
import { useTranslation } from "react-i18next";
interface DataItem {
  name: string;
  value: number;
  fill?: string;
}

interface DataTableViewProps {
  data: DataItem[];
}

export function DataTableView({ data }: DataTableViewProps) {
  // Sort data by value in descending order
  const sortedData = [...data].sort((a, b) => b.value - a.value);
  const { t } = useTranslation();

  // Calculate total for percentage
  const total = data.reduce((sum, item) => sum + item.value, 0);

  // Check if there's actual data (not just the fallback "No Data" entry)
  const hasRealData =
    data.length > 0 && !(data.length === 1 && data[0].name === "No Data");

  return (
    <div className="h-[220px] sm:h-[260px] w-full overflow-auto">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead className="w-[80px] sm:w-[100px] text-xs sm:text-sm">
              {t('dashboard.Status')}
            </TableHead>
            <TableHead className="text-right text-xs sm:text-sm">
              {t('dashboard.Count')}
            </TableHead>
            <TableHead className="text-right w-[80px] sm:w-[100px] text-xs sm:text-sm">
              {t('dashboard.Percentage')}
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {sortedData.map((item, index) => (
            <TableRow key={index}>
              <TableCell className="flex items-center gap-1 sm:gap-2 text-xs sm:text-sm py-2 sm:py-4">
                <div
                  className="w-3 sm:w-4 h-2 sm:h-3"
                  style={{
                    backgroundColor: item.fill || "#cccccc",
                    display: "inline-block",
                  }}
                />
                <span>{typeof item.name === "string" ? item.name : (item.name as any)?.en || (item.name as any)?.am || "Item"}</span>
              </TableCell>
              <TableCell className="text-right font-medium text-xs sm:text-sm py-2 sm:py-4">
                {item.value}
              </TableCell>
              <TableCell className="text-right text-xs sm:text-sm py-2 sm:py-4">
                {total > 0
                  ? `${Math.round((item.value / total) * 100)}%`
                  : "0%"}
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>

      {data.length === 0 && (
        <div className="flex justify-center items-center h-[180px] sm:h-[200px] text-gray-500 dark:text-gray-400 text-xs sm:text-sm">
          {t('common.noResult')}
        </div>
      )}

      {hasRealData && (
        <div className="mt-2 sm:mt-4 px-2 sm:px-4">
          <div className="flex justify-between text-xs sm:text-sm font-medium">
            <span>{t('dashboard.Total')}</span>
            <span>{total}</span>
          </div>
        </div>
      )}
    </div>
  );
}