'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Table } from '@/components/ui/Table';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import {
  listSales,
  type SaleResponse,
  type SaleListParams,
} from '@/lib/sales';
import type { PaginatedResponse } from '@/lib/api';

const STATUS_OPTIONS = ['draft', 'completed', 'cancelled'];

export function SaleList() {
  const router = useRouter();
  const [sales, setSales] = useState<SaleResponse[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(20);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [filters, setFilters] = useState<SaleListParams>({
    page: 1,
    page_size: 20,
  });

  const fetchSales = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data: PaginatedResponse<SaleResponse> = await listSales(filters);
      setSales(data.items);
      setTotal(data.total);
      setPage(data.page);
    } catch (err: unknown) {
      const apiErr = err as { error?: { message?: string } };
      setError(apiErr?.error?.message || 'Failed to load sales');
    } finally {
      setLoading(false);
    }
  }, [filters]);

  useEffect(() => {
    fetchSales();
  }, [fetchSales]);

  const handleFilterChange = (key: keyof SaleListParams, value: string) => {
    setFilters(prev => ({
      ...prev,
      page: 1,
      [key]: value || undefined,
    }));
  };

  const handlePageChange = (newPage: number) => {
    setFilters(prev => ({ ...prev, page: newPage }));
  };

  const columns = [
    {
      key: 'sale_date',
      label: 'Datum',
      render: (row: SaleResponse) =>
        new Date(row.sale_date).toLocaleDateString('de-DE'),
    },
    {
      key: 'vehicle',
      label: 'Fahrzeug',
      render: (row: SaleResponse) =>
        row.vehicle ? `${row.vehicle.make} ${row.vehicle.model}` : 'N/A',
    },
    {
      key: 'buyer',
      label: 'Käufer',
      render: (row: SaleResponse) =>
        row.buyer?.company_name || 'N/A',
    },
    {
      key: 'sale_price',
      label: 'Preis',
      render: (row: SaleResponse) =>
        new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(row.sale_price),
    },
    {
      key: 'status',
      label: 'Status',
      render: (row: SaleResponse) => (
        <span
          data-testid={`sale-status-${row.id}`}
          className={`px-2 py-1 rounded text-xs font-medium ${
            row.status === 'completed' ? 'bg-green-100 text-green-800' :
            row.status === 'cancelled' ? 'bg-red-100 text-red-800' :
            'bg-yellow-100 text-yellow-800'
          }`}
        >
          {row.status}
        </span>
      ),
    },
    {
      key: 'is_gwg',
      label: 'GwG',
      render: (row: SaleResponse) =>
        row.is_gwg ? (
          <span data-testid={`sale-gwg-${row.id}`} className="text-blue-600 font-medium">Ja</span>
        ) : 'Nein',
    },
    {
      key: 'actions',
      label: 'Aktionen',
      render: (row: SaleResponse) => (
        <button
          data-testid={`sale-row-${row.id}`}
          onClick={() => router.push(`/de/verkauf/${row.id}`)}
          className="text-primary hover:underline"
        >
          Details
        </button>
      ),
    },
  ];

  const totalPages = Math.ceil(total / pageSize);

  return (
    <div className="space-y-4" data-testid="sale-list">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Verkäufe</h1>
        <Button onClick={() => router.push('/de/verkauf/neu')} data-testid="sale-create-btn">
          Neuer Verkauf
        </Button>
      </div>

      {/* Filters */}
      <div className="flex gap-4 items-end" data-testid="sale-filters">
        <div className="flex-1">
          <label className="block text-sm font-medium mb-1">Status</label>
          <select
            data-testid="sale-status-filter"
            className="w-full border rounded px-3 py-2"
            value={filters.status || ''}
            onChange={e => handleFilterChange('status', e.target.value)}
          >
            <option value="">Alle</option>
            {STATUS_OPTIONS.map(s => (
              <option key={s} value={s}>{s}</option>
            ))}
          </select>
        </div>
        <div className="flex-1">
          <label className="block text-sm font-medium mb-1">Von</label>
          <Input
            type="date"
            data-testid="sale-date-from"
            value={filters.date_from || ''}
            onChange={e => handleFilterChange('date_from', e.target.value)}
          />
        </div>
        <div className="flex-1">
          <label className="block text-sm font-medium mb-1">Bis</label>
          <Input
            type="date"
            data-testid="sale-date-to"
            value={filters.date_to || ''}
            onChange={e => handleFilterChange('date_to', e.target.value)}
          />
        </div>
      </div>

      {error && (
        <div className="bg-red-50 text-red-600 p-3 rounded" data-testid="sale-error">
          {error}
        </div>
      )}

      {loading ? (
        <div data-testid="sale-loading">Wird geladen...</div>
      ) : (
        <Table columns={columns} data={sales} rowKey={(row) => row.id} />
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between" data-testid="sale-pagination">
          <Button
            disabled={page <= 1}
            onClick={() => handlePageChange(page - 1)}
          >
            Zurück
          </Button>
          <span>Seite {page} von {totalPages}</span>
          <Button
            disabled={page >= totalPages}
            onClick={() => handlePageChange(page + 1)}
          >
            Weiter
          </Button>
        </div>
      )}
    </div>
  );
}
