'use client';

import { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Table } from '@/components/ui/Table';
import {
  createDatevExport,
  listDatevExports,
  getDatevDownloadUrl,
  type DATEVExportResponse,
} from '@/lib/datev';
import type { PaginatedResponse } from '@/lib/api';

export function DatevExport() {
  const [exports, setExports] = useState<DATEVExportResponse[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [creating, setCreating] = useState(false);

  const fetchExports = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data: PaginatedResponse<DATEVExportResponse> = await listDatevExports();
      setExports(data.items);
      setTotal(data.total);
    } catch (err: unknown) {
      const apiErr = err as { error?: { message?: string } };
      setError(apiErr?.error?.message || 'Failed to load exports');
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleCreateExport = async (e: React.FormEvent) => {
    e.preventDefault();
    setCreating(true);
    setError(null);
    setSuccess(null);
    try {
      const result = await createDatevExport({ start_date: startDate, end_date: endDate });
      setSuccess(`Export erstellt: ${result.total_amount} EUR`);
      fetchExports();
    } catch (err: unknown) {
      const apiErr = err as { error?: { message?: string } };
      setError(apiErr?.error?.message || 'Failed to create export');
    } finally {
      setCreating(false);
    }
  };

  const columns = [
    {
      key: 'start_date',
      label: 'Von',
      render: (row: DATEVExportResponse) =>
        new Date(row.start_date).toLocaleDateString('de-DE'),
    },
    {
      key: 'end_date',
      label: 'Bis',
      render: (row: DATEVExportResponse) =>
        new Date(row.end_date).toLocaleDateString('de-DE'),
    },
    {
      key: 'total_amount',
      label: 'Gesamtbetrag',
      render: (row: DATEVExportResponse) =>
        new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(row.total_amount),
    },
    {
      key: 'created_at',
      label: 'Erstellt am',
      render: (row: DATEVExportResponse) =>
        row.created_at ? new Date(row.created_at).toLocaleString('de-DE') : 'N/A',
    },
    {
      key: 'actions',
      label: 'Aktion',
      render: (row: DATEVExportResponse) => (
        <a
          href={getDatevDownloadUrl(row.id)}
          data-testid={`datev-download-${row.id}`}
          className="text-primary hover:underline"
        >
          CSV herunterladen
        </a>
      ),
    },
  ];

  return (
    <div className="space-y-4" data-testid="datev-export">
      <h1 className="text-2xl font-bold">DATEV Export</h1>

      {/* Create export form */}
      <form onSubmit={handleCreateExport} className="flex gap-4 items-end" data-testid="datev-export-form">
        <div className="flex-1">
          <label className="block text-sm font-medium mb-1">Von Datum *</label>
          <Input
            data-testid="datev-start-date"
            type="date"
            value={startDate}
            onChange={e => setStartDate(e.target.value)}
            required
          />
        </div>
        <div className="flex-1">
          <label className="block text-sm font-medium mb-1">Bis Datum *</label>
          <Input
            data-testid="datev-end-date"
            type="date"
            value={endDate}
            onChange={e => setEndDate(e.target.value)}
            required
          />
        </div>
        <Button type="submit" disabled={creating} data-testid="datev-create-btn">
          {creating ? 'Wird erstellt...' : 'Export erstellen'}
        </Button>
      </form>

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

      {success && (
        <div className="bg-green-50 text-green-600 p-3 rounded" data-testid="datev-success">
          {success}
        </div>
      )}

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

      {total === 0 && !loading && (
        <p className="text-gray-500" data-testid="datev-empty">Noch keine Exporte vorhanden.</p>
      )}
    </div>
  );
}
