/**
 * Categories List Page
 * Display and manage categories
 */

'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { categoriesAPI } from '@/lib/api/categories';
import { Button, Card, CardHeader, CardTitle, CardContent, Table, TableHeader, TableBody, TableRow, TableHead, TableCell, Badge, LoadingSpinner } from '@/components/ui';
import { Plus, Tag, Folder } from 'lucide-react';

export default function CategoriesPage() {
  const router = useRouter();
  const [page, setPage] = useState(1);
  const [limit] = useState(50);
  const [parentIdFilter, setParentIdFilter] = useState('');
  const [showChildren, setShowChildren] = useState(false);

  // Fetch categories
  const { data, isLoading, error } = useQuery({
    queryKey: ['categories', page, limit, parentIdFilter, showChildren],
    queryFn: async () => {
      const params = {
        page,
        limit,
        ...(parentIdFilter === 'null' && { parent_id: 'null' }),
        ...(parentIdFilter && parentIdFilter !== 'null' && { parent_id: parentIdFilter }),
        ...(showChildren && { with_children: 'true' }),
      };
      const response = await categoriesAPI.list(params);
      return response.data || response;
    },
  });

  const categories = data?.categories || [];
  const pagination = data?.pagination || {};

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-950 space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Categories</h1>
          <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
            Organize your products with categories
          </p>
        </div>
        <Button
          onClick={() => router.push('/categories/new')}
          variant="primary"
          className="flex items-center gap-2"
        >
          <Plus className="w-5 h-5" />
          New Category
        </Button>
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="pt-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Filter by Parent
              </label>
              <select
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                value={parentIdFilter}
                onChange={(e) => {
                  setParentIdFilter(e.target.value);
                  setPage(1);
                }}
              >
                <option value="">All Categories</option>
                <option value="null">Root Categories Only</option>
              </select>
            </div>
            <div className="flex items-end">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={showChildren}
                  onChange={(e) => setShowChildren(e.target.checked)}
                  className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                />
                <span className="text-sm text-gray-700">Include child categories</span>
              </label>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Categories Table */}
      <Card>
        <CardHeader>
          <CardTitle>Category List</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex justify-center py-12">
              <LoadingSpinner size="lg" />
            </div>
          ) : error ? (
            <div className="text-center py-12 text-red-600 dark:text-red-400">
              Error loading categories. Please try again.
            </div>
          ) : categories.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-gray-400">
              <Tag className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>No categories found</p>
              <Button
                variant="primary"
                className="mt-4"
                onClick={() => router.push('/categories/new')}
              >
                Create Your First Category
              </Button>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Name</TableHead>
                    <TableHead>Slug</TableHead>
                    <TableHead>Parent</TableHead>
                    <TableHead>Sort Order</TableHead>
                    <TableHead>Description</TableHead>
                    <TableHead align="right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {categories.map((category) => (
                    <TableRow
                      key={category.id}
                      onClick={() => router.push(`/categories/${category.id}`)}
                      className="hover:bg-gray-50 dark:hover:bg-gray-800 cursor-pointer"
                    >
                      <TableCell>
                        <div className="flex items-center gap-2">
                          {category.parent_id ? (
                            <Folder className="w-4 h-4 text-gray-400" />
                          ) : (
                            <Tag className="w-4 h-4 text-blue-500" />
                          )}
                          <span className="font-medium">{category.name}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <span className="font-mono text-sm text-gray-500">{category.slug}</span>
                      </TableCell>
                      <TableCell>
                        {category.parent_id ? (
                          <Badge variant="info">Child</Badge>
                        ) : (
                          <Badge variant="success">Root</Badge>
                        )}
                      </TableCell>
                      <TableCell>
                        <span className="text-gray-600">{category.sort_order || 0}</span>
                      </TableCell>
                      <TableCell>
                        <span className="text-sm text-gray-500 truncate max-w-xs">
                          {category.description || 'N/A'}
                        </span>
                      </TableCell>
                      <TableCell align="right">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={(e) => {
                            e.stopPropagation();
                            router.push(`/categories/${category.id}`);
                          }}
                        >
                          View
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>

              {/* Pagination */}
              {pagination.totalPages > 1 && (
                <div className="mt-4 flex items-center justify-between">
                  <div className="text-sm text-gray-700 dark:text-gray-300">
                    Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, pagination.total)} of {pagination.total} categories
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setPage(p => Math.max(1, p - 1))}
                      disabled={page === 1}
                    >
                      Previous
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setPage(p => Math.min(pagination.totalPages, p + 1))}
                      disabled={page === pagination.totalPages}
                    >
                      Next
                    </Button>
                  </div>
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

