/**
 * Returns List Page
 * View and manage returns
 */

'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { returnsAPI } from '@/lib/api/returns';
import { Button, Card, CardHeader, CardTitle, CardContent, Table, TableHeader, TableBody, TableRow, TableHead, TableCell, Badge, LoadingSpinner, Input } from '@/components/ui';
import { formatCurrency, formatDateTime } from '@/lib/utils/format';
import { ArrowLeftRight, Plus, Search, X } from 'lucide-react';
import Link from 'next/link';

export default function ReturnsPage() {
  const router = useRouter();
  const [page, setPage] = useState(1);
  const [limit] = useState(20);
  const [statusFilter, setStatusFilter] = useState('');
  const [saleIdFilter, setSaleIdFilter] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');

  // Fetch returns
  const { data, isLoading, error } = useQuery({
    queryKey: ['returns', page, limit, statusFilter, saleIdFilter, startDate, endDate],
    queryFn: async () => {
      const params = {
        page,
        limit,
        ...(statusFilter && { status: statusFilter }),
        ...(saleIdFilter && { sale_id: parseInt(saleIdFilter) }),
        ...(startDate && { start_date: startDate }),
        ...(endDate && { end_date: endDate }),
      };
      const response = await returnsAPI.list(params);
      return response.data || response;
    },
  });

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

  const getStatusVariant = (status) => {
    switch (status) {
      case 'COMPLETED':
        return 'success';
      case 'DRAFT':
        return 'warning';
      default:
        return 'default';
    }
  };

  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">Returns</h1>
          <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
            Manage product returns and credit notes
          </p>
        </div>
        <Button
          onClick={() => router.push('/returns/new')}
          variant="primary"
          className="flex items-center gap-2"
        >
          <Plus className="w-5 h-5" />
          New Return
        </Button>
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="pt-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Status
              </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={statusFilter}
                onChange={(e) => {
                  setStatusFilter(e.target.value);
                  setPage(1);
                }}
              >
                <option value="">All Statuses</option>
                <option value="DRAFT">Draft</option>
                <option value="COMPLETED">Completed</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Sale ID
              </label>
              <Input
                type="number"
                placeholder="Search by Sale ID"
                value={saleIdFilter}
                onChange={(e) => {
                  setSaleIdFilter(e.target.value);
                  setPage(1);
                }}
                leftIcon={<Search className="w-4 h-4" />}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                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-1">
                End Date
              </label>
              <Input
                type="date"
                value={endDate}
                onChange={(e) => {
                  setEndDate(e.target.value);
                  setPage(1);
                }}
              />
            </div>
          </div>
          {(statusFilter || saleIdFilter || startDate || endDate) && (
            <div className="mt-4">
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setStatusFilter('');
                  setSaleIdFilter('');
                  setStartDate('');
                  setEndDate('');
                  setPage(1);
                }}
                className="flex items-center gap-2"
              >
                <X className="w-4 h-4" />
                Clear Filters
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Returns Table */}
      <Card>
        <CardHeader>
          <CardTitle>Returns 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 returns. Please try again.
            </div>
          ) : returns.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-gray-400">
              <ArrowLeftRight className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>No returns found</p>
              <Button
                variant="primary"
                className="mt-4"
                onClick={() => router.push('/returns/new')}
              >
                Create Your First Return
              </Button>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Return ID</TableHead>
                    <TableHead>Sale</TableHead>
                    <TableHead>Invoice #</TableHead>
                    <TableHead>Date</TableHead>
                    <TableHead align="right">Total Amount</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead align="right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {returns.map((returnRecord) => (
                    <TableRow key={returnRecord.id}>
                      <TableCell className="font-medium">
                        RET-{returnRecord.id}
                      </TableCell>
                      <TableCell>
                        <Link
                          href={`/sales/${returnRecord.sale_id}`}
                          className="text-blue-600 hover:text-blue-800 dark:text-blue-400 hover:underline"
                        >
                          Sale #{returnRecord.sale_id}
                        </Link>
                      </TableCell>
                      <TableCell>
                        <span className="font-mono text-sm">
                          {returnRecord.sale?.invoice_no || `#${returnRecord.sale_id}`}
                        </span>
                      </TableCell>
                      <TableCell className="text-sm text-gray-600 dark:text-gray-400">
                        {formatDateTime(returnRecord.created_at || returnRecord.returned_at)}
                      </TableCell>
                      <TableCell align="right" className="font-medium">
                        {formatCurrency(returnRecord.total_amount)}
                      </TableCell>
                      <TableCell>
                        <Badge variant={getStatusVariant(returnRecord.status)}>
                          {returnRecord.status}
                        </Badge>
                      </TableCell>
                      <TableCell align="right">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => router.push(`/returns/${returnRecord.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} returns
                  </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>
  );
}

