/**
 * Credit Notes List Page
 * View all credit notes (completed 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 { FileText, Search, X } from 'lucide-react';
import Link from 'next/link';

export default function CreditNotesPage() {
  const router = useRouter();
  const [page, setPage] = useState(1);
  const [limit] = useState(20);
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [invoiceSearch, setInvoiceSearch] = useState('');

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

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

  const getRefundMethodBadge = (method) => {
    const variants = {
      CASH: 'default',
      CARD: 'primary',
      MPESA: 'success',
      CREDIT_NOTE: 'warning',
      REPLACEMENT: 'info',
    };
    return variants[method] || '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">Credit Notes</h1>
          <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
            View all credit notes issued for returns
          </p>
        </div>
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="pt-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <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>
              <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={invoiceSearch}
                onChange={(e) => {
                  setInvoiceSearch(e.target.value);
                  setPage(1);
                }}
                leftIcon={<Search className="w-4 h-4" />}
              />
            </div>
          </div>
          {(startDate || endDate || invoiceSearch) && (
            <div className="mt-4">
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setStartDate('');
                  setEndDate('');
                  setInvoiceSearch('');
                  setPage(1);
                }}
                className="flex items-center gap-2"
              >
                <X className="w-4 h-4" />
                Clear Filters
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Credit Notes Table */}
      <Card>
        <CardHeader>
          <CardTitle>Credit Notes</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 credit notes. Please try again.
            </div>
          ) : returns.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-gray-400">
              <FileText className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>No credit notes found</p>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Credit Note #</TableHead>
                    <TableHead>Return ID</TableHead>
                    <TableHead>Sale Invoice</TableHead>
                    <TableHead>Date</TableHead>
                    <TableHead align="right">Amount</TableHead>
                    <TableHead>Refund Method</TableHead>
                    <TableHead align="right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {returns.map((returnRecord) => {
                    const creditNote = returnRecord.creditNotes?.[0];
                    return (
                      <TableRow key={returnRecord.id}>
                        <TableCell className="font-medium font-mono">
                          {creditNote?.kra_receipt_no || creditNote?.receipt_number || `CN-${creditNote?.id || returnRecord.id}`}
                        </TableCell>
                        <TableCell>
                          RET-{returnRecord.id}
                        </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.refunded_at || returnRecord.returned_at || returnRecord.created_at)}
                        </TableCell>
                        <TableCell align="right" className="font-medium">
                          {formatCurrency(returnRecord.refund_amount || returnRecord.total_amount)}
                        </TableCell>
                        <TableCell>
                          {returnRecord.refund_method ? (
                            <Badge variant={getRefundMethodBadge(returnRecord.refund_method)}>
                              {returnRecord.refund_method}
                            </Badge>
                          ) : (
                            <Badge variant="warning">CREDIT_NOTE</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} credit notes
                  </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>
  );
}
