/**
 * GRNs (Goods Received Notes) List Page
 * View and manage GRNs
 */

'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, Input, Select } from '@/components/ui';
import { formatCurrency, formatDateTime, formatDate } from '@/lib/utils/format';
import { Package, Plus, Search, Filter, X } from 'lucide-react';

export default function GRNsPage() {
  const router = useRouter();
  const [page, setPage] = useState(1);
  const [limit] = useState(20);
  const [poNumber, setPoNumber] = useState('');
  const [status, setStatus] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');

  // Fetch GRNs
  const { data, isLoading, error } = useQuery({
    queryKey: ['grns', page, limit, poNumber, status, startDate, endDate],
    queryFn: async () => {
      const params = {
        page,
        limit,
        ...(poNumber && { po_number: poNumber }),
        ...(status && { status }),
        ...(startDate && { start_date: startDate }),
        ...(endDate && { end_date: endDate }),
      };
      const response = await procurementAPI.listGRNs(params);
      return response.data || response;
    },
  });

  const handleClearFilters = () => {
    setPoNumber('');
    setStatus('');
    setStartDate('');
    setEndDate('');
    setPage(1);
  };

  const hasActiveFilters = poNumber || status || startDate || endDate;

  const grns = data?.grns || [];
  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">GRNs</h1>
          <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
            Goods Received Notes - Process incoming inventory
          </p>
        </div>
        <Button
          onClick={() => router.push('/procurement/grns/new')}
          variant="primary"
          className="flex items-center gap-2"
        >
          <Plus className="w-5 h-5" />
          New GRN
        </Button>
      </div>

      {/* Filters */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Filter className="w-5 h-5" />
              Filters
            </CardTitle>
            {hasActiveFilters && (
              <Button
                variant="outline"
                size="sm"
                onClick={handleClearFilters}
                className="flex items-center gap-2"
              >
                <X className="w-4 h-4" />
                Clear Filters
              </Button>
            )}
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                PO Number
              </label>
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                <Input
                  type="text"
                  placeholder="Search PO number..."
                  value={poNumber}
                  onChange={(e) => {
                    setPoNumber(e.target.value);
                    setPage(1);
                  }}
                  className="pl-10"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Status
              </label>
              <Select
                value={status}
                onChange={(e) => {
                  setStatus(e.target.value);
                  setPage(1);
                }}
                options={[
                  { value: '', label: 'All Status' },
                  { value: 'pending', label: 'Pending' },
                  { value: 'processed', label: 'Processed' },
                ]}
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Start Date
              </label>
              <Input
                type="date"
                value={startDate}
                onChange={(e) => {
                  setStartDate(e.target.value);
                  setPage(1);
                }}
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                End Date
              </label>
              <Input
                type="date"
                value={endDate}
                onChange={(e) => {
                  setEndDate(e.target.value);
                  setPage(1);
                }}
              />
            </div>

            <div className="flex items-end">
              {hasActiveFilters && (
                <div className="text-sm text-gray-600 dark:text-gray-400">
                  Filters active
                </div>
              )}
            </div>
          </div>
        </CardContent>
      </Card>

      {/* GRNs Table */}
      <Card>
        <CardHeader>
          <CardTitle>GRNs 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 GRNs. Please try again.
            </div>
          ) : grns.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-gray-400">
              <Package className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>No GRNs found</p>
              <Button
                variant="primary"
                className="mt-4"
                onClick={() => router.push('/procurement/grns/new')}
              >
                Create Your First GRN
              </Button>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>GRN Number</TableHead>
                    <TableHead>Purchase Order</TableHead>
                    <TableHead>Vendor</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Created Date</TableHead>
                    <TableHead align="right">Total Amount</TableHead>
                    <TableHead align="right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {grns.map((grn) => {
                    const isProcessed = !!grn.processed_at;
                    return (
                      <TableRow key={grn.id}>
                        <TableCell className="font-medium">
                          {grn.grn_number || `GRN-${grn.id}`}
                        </TableCell>
                        <TableCell>
                          {grn.purchaseOrder?.po_number || (grn.purchase_order_id ? `PO-${grn.purchase_order_id}` : 'N/A')}
                        </TableCell>
                        <TableCell>{grn.vendor?.name || 'N/A'}</TableCell>
                        <TableCell>
                          {isProcessed ? (
                            <Badge variant="success">Processed</Badge>
                          ) : (
                            <Badge variant="warning">Pending</Badge>
                          )}
                        </TableCell>
                        <TableCell className="text-sm text-gray-600 dark:text-gray-400">
                          {formatDate(grn.created_at)}
                        </TableCell>
                        <TableCell align="right" className="font-medium">
                          {formatCurrency(grn.total_amount || 0)}
                        </TableCell>
                        <TableCell align="right">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => router.push(`/procurement/grns/${grn.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} GRNs
                  </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>
  );
}


