"use client";

import React, { useState } from 'react';
import { Task } from '../data/schema';
import { labels, priorities, statuses } from '../data/data';
import { DataTableToolbar } from './DataTableToolbar';
import { DataTablePagination } from './DataTablePagination';

interface DataTableProps {
  data: Task[];
}

export const DataTable: React.FC<DataTableProps> = ({ data }) => {
  const [filteredData, setFilteredData] = useState(data);
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);

  const renderItem = (item: Task) => {
    const label = labels.find(l => l.value === item.label);
    const status = statuses.find(s => s.value === item.status);
    const priority = priorities.find(p => p.value === item.priority);

    return (
      <tr key={item.id} className="border-b">
        <td className="p-2">{item.id}</td>
        <td className="p-2">
          <span className="bg-gray-100 rounded-full px-2 py-1 text-xs mr-2">
            {label?.label}
          </span>
          {item.title}
        </td>
        <td className="p-2">{status?.label}</td>
        <td className="p-2">{priority?.label}</td>
        <td className="p-2">
          <button className="text-blue-500 hover:text-blue-700">Actions</button>
        </td>
      </tr>
    );
  };

  return (
    <div className="flex flex-col h-full">
      <DataTableToolbar onFilter={setFilteredData} data={data} />
      <div className="overflow-auto flex-grow">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Title</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Priority</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {filteredData.slice(page * rowsPerPage, (page + 1) * rowsPerPage).map(renderItem)}
          </tbody>
        </table>
      </div>
      <DataTablePagination
        page={page}
        setPage={setPage}
        rowsPerPage={rowsPerPage}
        setRowsPerPage={setRowsPerPage}
        totalItems={filteredData.length}
      />
    </div>
  );
};
