/**
 * Discounts List Page
 * View and manage discounts
 */

'use client';

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

export default function DiscountsPage() {
  const router = useRouter();
  const [page, setPage] = useState(1);
  const [limit] = useState(20);
  const [searchTerm, setSearchTerm] = useState('');
  const [typeFilter, setTypeFilter] = useState('');
  const [activeFilter, setActiveFilter] = useState('true');

  // Fetch discounts
  const { data, isLoading, error } = useQuery({
    queryKey: ['discounts', page, limit, searchTerm, typeFilter, activeFilter],
    queryFn: async () => {
      const params = {
        page,
        limit,
        ...(searchTerm && { search: searchTerm }),
        ...(typeFilter && { discount_type: typeFilter }),
        ...(activeFilter !== '' && { active: activeFilter }),
      };
      const response = await discountsAPI.list(params);
      return response.data || response;
    },
  });

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

  const getDiscountTypeLabel = (type) => {
    switch (type) {
      case 'PERCENTAGE':
        return 'Percentage';
      case 'FIXED_AMOUNT':
        return 'Fixed Amount';
      case 'BUY_X_GET_Y':
        return 'Buy X Get Y';
      default:
        return type;
    }
  };

  const formatDiscountValue = (discount) => {
    if (discount.discount_type === 'PERCENTAGE') {
      return `${discount.discount_value}%`;
    } else if (discount.discount_type === 'FIXED_AMOUNT') {
      return formatCurrency(discount.discount_value);
    } else if (discount.discount_type === 'BUY_X_GET_Y') {
      return `${discount.buy_quantity || 'X'} / ${discount.get_quantity || 'Y'}`;
    }
    return discount.discount_value || 'N/A';
  };

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

      {/* Filters */}
      <Card>
        <CardContent className="pt-6">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Search
              </label>
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                <Input
                  type="text"
                  placeholder="Search by name or code..."
                  value={searchTerm}
                  onChange={(e) => {
                    setSearchTerm(e.target.value);
                    setPage(1);
                  }}
                  className="pl-10"
                />
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Type
              </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={typeFilter}
                onChange={(e) => {
                  setTypeFilter(e.target.value);
                  setPage(1);
                }}
              >
                <option value="">All Types</option>
                <option value="PERCENTAGE">Percentage</option>
                <option value="FIXED_AMOUNT">Fixed Amount</option>
                <option value="BUY_X_GET_Y">Buy X Get Y</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 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={activeFilter}
                onChange={(e) => {
                  setActiveFilter(e.target.value);
                  setPage(1);
                }}
              >
                <option value="true">Active</option>
                <option value="false">Inactive</option>
                <option value="">All</option>
              </select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Discounts Table */}
      <Card>
        <CardHeader>
          <CardTitle>Discounts 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 discounts. Please try again.
            </div>
          ) : discounts.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-gray-400">
              <TrendingUp className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>No discounts found</p>
              <Button
                variant="primary"
                className="mt-4"
                onClick={() => router.push('/discounts/new')}
              >
                Create Your First Discount
              </Button>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Code</TableHead>
                    <TableHead>Name</TableHead>
                    <TableHead>Type</TableHead>
                    <TableHead align="right">Value</TableHead>
                    <TableHead>Valid From</TableHead>
                    <TableHead>Valid To</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead align="right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {discounts.map((discount) => (
                    <TableRow key={discount.id}>
                      <TableCell>
                        <span className="font-mono font-medium">{discount.code}</span>
                      </TableCell>
                      <TableCell>
                        <div className="font-medium">{discount.name}</div>
                        {discount.description && (
                          <div className="text-xs text-gray-500 truncate max-w-xs">
                            {discount.description}
                          </div>
                        )}
                      </TableCell>
                      <TableCell>
                        <Badge variant="info">{getDiscountTypeLabel(discount.discount_type)}</Badge>
                      </TableCell>
                      <TableCell align="right" className="font-medium">
                        {formatDiscountValue(discount)}
                      </TableCell>
                      <TableCell className="text-sm text-gray-600 dark:text-gray-400">
                        {discount.valid_from ? formatDate(discount.valid_from) : '—'}
                      </TableCell>
                      <TableCell className="text-sm text-gray-600 dark:text-gray-400">
                        {discount.valid_to ? formatDate(discount.valid_to) : '—'}
                      </TableCell>
                      <TableCell>
                        {discount.active ? (
                          <Badge variant="success">Active</Badge>
                        ) : (
                          <Badge variant="default">Inactive</Badge>
                        )}
                      </TableCell>
                      <TableCell align="right">
                        <div className="flex justify-end gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => router.push(`/discounts/${discount.id}`)}
                          >
                            View
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => router.push(`/discounts/${discount.id}/edit`)}
                          >
                            Edit
                          </Button>
                        </div>
                      </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} discounts
                  </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>
  );
}


