'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { createSale, type SaleCreateData } from '@/lib/sales';
import { listVehicles, type VehicleResponse } from '@/lib/vehicles';
import { useEffect, useCallback } from 'react';
import type { PaginatedResponse } from '@/lib/api';

export function SaleForm() {
  const router = useRouter();
  const [vehicles, setVehicles] = useState<VehicleResponse[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [formData, setFormData] = useState<SaleCreateData>({
    vehicle_id: '',
    buyer_contact_id: '',
    sale_price: 0,
    sale_date: new Date().toISOString().split('T')[0],
    status: 'draft',
    is_gwg: false,
  });

  const fetchVehicles = useCallback(async () => {
    try {
      const data: PaginatedResponse<VehicleResponse> = await listVehicles({ page: 1, page_size: 100 });
      setVehicles(data.items.filter(v => v.availability === 'available'));
    } catch {
      // ignore - vehicles list is optional
    }
  }, []);

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const sale = await createSale(formData);
      router.push(`/de/verkauf/${sale.id}`);
    } catch (err: unknown) {
      const apiErr = err as { error?: { message?: string } };
      setError(apiErr?.error?.message || 'Failed to create sale');
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4 max-w-2xl" data-testid="sale-form">
      <h1 className="text-2xl font-bold">Neuer Verkauf</h1>

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

      <div>
        <label className="block text-sm font-medium mb-1">Fahrzeug *</label>
        <select
          data-testid="sale-vehicle-select"
          className="w-full border rounded px-3 py-2"
          value={formData.vehicle_id}
          onChange={e => setFormData(prev => ({ ...prev, vehicle_id: e.target.value }))}
          required
        >
          <option value="">Fahrzeug auswählen</option>
          {vehicles.map(v => (
            <option key={v.id} value={v.id}>
              {v.make} {v.model} - {v.fin}
            </option>
          ))}
        </select>
      </div>

      <div>
        <label className="block text-sm font-medium mb-1">Käufer Kontakt ID *</label>
        <Input
          data-testid="sale-buyer-input"
          value={formData.buyer_contact_id}
          onChange={e => setFormData(prev => ({ ...prev, buyer_contact_id: e.target.value }))}
          placeholder="UUID des Käufer-Kontakts"
          required
        />
      </div>

      <div>
        <label className="block text-sm font-medium mb-1">Verkaufspreis (EUR) *</label>
        <Input
          data-testid="sale-price-input"
          type="number"
          step="0.01"
          min="0"
          value={formData.sale_price}
          onChange={e => setFormData(prev => ({ ...prev, sale_price: parseFloat(e.target.value) || 0 }))}
          required
        />
      </div>

      <div>
        <label className="block text-sm font-medium mb-1">Verkaufsdatum</label>
        <Input
          data-testid="sale-date-input"
          type="date"
          value={formData.sale_date}
          onChange={e => setFormData(prev => ({ ...prev, sale_date: e.target.value }))}
        />
      </div>

      <div>
        <label className="block text-sm font-medium mb-1">Status</label>
        <select
          data-testid="sale-status-select"
          className="w-full border rounded px-3 py-2"
          value={formData.status}
          onChange={e => setFormData(prev => ({ ...prev, status: e.target.value }))}
        >
          <option value="draft">Entwurf</option>
          <option value="completed">Abgeschlossen</option>
        </select>
      </div>

      <div className="flex items-center gap-2">
        <input
          data-testid="sale-gwg-toggle"
          type="checkbox"
          id="is_gwg"
          checked={formData.is_gwg}
          onChange={e => setFormData(prev => ({ ...prev, is_gwg: e.target.checked }))}
          className="w-4 h-4"
        />
        <label htmlFor="is_gwg" className="text-sm font-medium">
          Geringwertiges Wirtschaftsgut (GwG) - §6 Abs. 2 EStG
        </label>
      </div>

      <div className="flex gap-2">
        <Button type="submit" disabled={loading} data-testid="sale-submit-btn">
          {loading ? 'Wird gespeichert...' : 'Verkauf anlegen'}
        </Button>
        <Button type="button" onClick={() => router.back()} variant="secondary">
          Abbrechen
        </Button>
      </div>
    </form>
  );
}
