/**
 * Vendors List Page
 * View and manage vendors
 */

'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { procurementAPI } from '@/lib/api/procurement';
import { Button, Card, CardHeader, CardTitle, CardContent, Table, TableHeader, TableBody, TableRow, TableHead, TableCell, Badge, LoadingSpinner } from '@/components/ui';
import { formatCurrency, formatDateTime } from '@/lib/utils/format';
import { ShoppingBag, Plus } from 'lucide-react';

export default function VendorsPage() {
  const router = useRouter();
  const [page, setPage] = useState(1);
  const [limit] = useState(20);

  // Fetch vendors
  const { data, isLoading, error } = useQuery({
    queryKey: ['vendors', page, limit],
    queryFn: async () => {
      const params = { page, limit };
      const response = await procurementAPI.listVendors(params);
      return response.data || response;
    },
  });

  const vendors = data?.vendors || data?.vendor || [];
  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">Vendors</h1>
          <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
            Manage suppliers and vendors
          </p>
        </div>
        <Button
          onClick={() => router.push('/procurement/vendors/new')}
          variant="primary"
          className="flex items-center gap-2"
        >
          <Plus className="w-5 h-5" />
          New Vendor
        </Button>
      </div>

      {/* Vendors Table */}
      <Card>
        <CardHeader>
          <CardTitle>Vendors 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 vendors. Please try again.
            </div>
          ) : vendors.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-gray-400">
              <ShoppingBag className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>No vendors found</p>
              <Button
                variant="primary"
                className="mt-4"
                onClick={() => router.push('/procurement/vendors/new')}
              >
                Create Your First Vendor
              </Button>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Name</TableHead>
                    <TableHead>Contact</TableHead>
                    <TableHead>Email</TableHead>
                    <TableHead>Phone</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead align="right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {vendors.map((vendor) => (
                    <TableRow key={vendor.id}>
                      <TableCell className="font-medium">{vendor.name}</TableCell>
                      <TableCell>{vendor.contact_person || 'N/A'}</TableCell>
                      <TableCell>{vendor.email || 'N/A'}</TableCell>
                      <TableCell>{vendor.phone || 'N/A'}</TableCell>
                      <TableCell>
                        {vendor.active !== false ? (
                          <Badge variant="success">Active</Badge>
                        ) : (
                          <Badge variant="default">Inactive</Badge>
                        )}
                      </TableCell>
                      <TableCell align="right">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => router.push(`/procurement/vendors/${vendor.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} vendors
                  </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>
  );
}


