'use client';
import React, { useState, useEffect } from "react";
import { Table, TableBody, TableCell, TableHeader, TableRow } from "../../ui/Table";
import Badge from "../../ui/Badge";
import Image from "next/image";

export default function DataTable() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [dataType, setDataType] = useState('todos');
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);
        const response = await fetch(`https://jsonplaceholder.typicode.com/${dataType}`);
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const json = await response.json();
        setData(Array.isArray(json) ? json.slice(0, 5) : []);
      } catch (err) {
        console.error("Error fetching data:", err);
        setError(err.message);
        setData([]);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [dataType]);

  const renderTableContent = () => {
    // ... (keep the existing switch case for headers)
  };

  const renderTableRows = () => {
    if (loading) {
      return (
        <TableRow>
          <TableCell colSpan={5} className="text-center py-4">
            Loading...
          </TableCell>
        </TableRow>
      );
    }

    if (error) {
      return (
        <TableRow>
          <TableCell colSpan={5} className="text-center py-4 text-red-500">
            Error: {error}
          </TableCell>
        </TableRow>
      );
    }

    if (!data.length) {
      return (
        <TableRow>
          <TableCell colSpan={5} className="text-center py-4">
            No data available
          </TableCell>
        </TableRow>
      );
    }

    return data.map((item) => {
      if (!item) return null;

      switch (dataType) {
        case 'todos':
          return (
            <TableRow key={item.id}>
              <TableCell className="px-5 py-4 sm:px-6 text-start">
                {item.userId || 'N/A'}
              </TableCell>
              <TableCell className="px-4 py-3 text-gray-500 text-start text-theme-sm dark:text-gray-400">
                {item.title || 'No title'}
              </TableCell>
              <TableCell className="px-4 py-3 text-gray-500 text-start text-theme-sm dark:text-gray-400">
                <Badge
                  size="sm"
                  color={item.completed ? "success" : "error"}
                >
                  {item.completed ? "Completed" : "Pending"}
                </Badge>
              </TableCell>
            </TableRow>
          );
        case 'comments':
          return (
            <TableRow key={item.id}>
              <TableCell className="px-5 py-4 sm:px-6 text-start">
                {item.name || 'Anonymous'}
              </TableCell>
              <TableCell className="px-4 py-3 text-gray-500 text-start text-theme-sm dark:text-gray-400">
                {item.email || 'No email'}
              </TableCell>
              <TableCell className="px-4 py-3 text-gray-500 text-start text-theme-sm dark:text-gray-400">
                {item.body ? `${item.body.substring(0, 50)}...` : 'No content'}
              </TableCell>
            </TableRow>
          );
        case 'albums':
          return (
            <TableRow key={item.id}>
              <TableCell className="px-5 py-4 sm:px-6 text-start">
                {item.userId || 'N/A'}
              </TableCell>
              <TableCell className="px-4 py-3 text-gray-500 text-start text-theme-sm dark:text-gray-400">
                {item.title || 'Untitled'}
              </TableCell>
            </TableRow>
          );
        case 'photos':
          return (
            <TableRow key={item.id}>
              <TableCell className="px-5 py-4 sm:px-6 text-start">
                {item.albumId || 'N/A'}
              </TableCell>
              <TableCell className="px-4 py-3 text-gray-500 text-start text-theme-sm dark:text-gray-400">
                {item.title || 'Untitled'}
              </TableCell>
              <TableCell className="px-4 py-3 text-gray-500 text-start text-theme-sm dark:text-gray-400">
                <div className="w-10 h-10 overflow-hidden rounded-full">
                  {item.thumbnailUrl ? (
                    <Image
                      width={40}
                      height={40}
                      src={item.thumbnailUrl}
                      alt={item.title || 'Photo'}
                    />
                  ) : (
                    <div className="w-full h-full bg-gray-200 flex items-center justify-center">
                      <span className="text-gray-500">No image</span>
                    </div>
                  )}
                </div>
              </TableCell>
            </TableRow>
          );
        case 'users':
          return (
            <TableRow key={item.id}>
              <TableCell className="px-5 py-4 sm:px-6 text-start">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 overflow-hidden rounded-full bg-gray-200 flex items-center justify-center">
                    <span className="text-gray-600 font-medium">
                      {item.name ? item.name.charAt(0) : '?'}
                    </span>
                  </div>
                  <div>
                    <span className="block font-medium text-gray-800 text-theme-sm dark:text-white/90">
                      {item.name || 'Unknown'}
                    </span>
                    <span className="block text-gray-500 text-theme-xs dark:text-gray-400">
                      @{item.username || 'user'}
                    </span>
                  </div>
                </div>
              </TableCell>
              <TableCell className="px-4 py-3 text-gray-500 text-start text-theme-sm dark:text-gray-400">
                {item.email || 'No email'}
              </TableCell>
              <TableCell className="px-4 py-3 text-gray-500 text-start text-theme-sm dark:text-gray-400">
                {item.company?.name || 'No company'}
              </TableCell>
              <TableCell className="px-4 py-3 text-gray-500 text-theme-sm dark:text-gray-400">
                {item.phone || 'No phone'}
              </TableCell>
            </TableRow>
          );
        default:
          return null;
      }
    });
  };

  return (
    <div className="overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-white/[0.05] dark:bg-white/[0.03]">
      <div className="flex justify-between items-center p-4 border-b border-gray-100 dark:border-white/[0.05]">
        <h3 className="font-medium text-gray-800 dark:text-white/90">
          {dataType.charAt(0).toUpperCase() + dataType.slice(1)} Data
        </h3>
        <div className="flex gap-2">
          {['todos', 'comments', 'albums', 'photos', 'users'].map((type) => (
            <button
              key={type}
              onClick={() => setDataType(type)}
              className={`px-3 py-1 text-sm rounded-md ${
                dataType === type
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300'
              }`}
            >
              {type.charAt(0).toUpperCase() + type.slice(1)}
            </button>
          ))}
        </div>
      </div>
      <div className="max-w-full overflow-x-auto">
        <div className="min-w-[1102px]">
          <Table>
            <TableHeader className="border-b border-gray-100 dark:border-white/[0.05]">
              <TableRow>
                {renderTableContent()}
              </TableRow>
            </TableHeader>
            <TableBody className="divide-y divide-gray-100 dark:divide-white/[0.05]">
              {renderTableRows()}
            </TableBody>
          </Table>
        </div>
      </div>
    </div>
  );
}