'use client'

import { useState } from 'react'
import { wearPartSchema, WearPartType, WearPartStatus } from '@/lib/validations'

interface WearPartFormProps {
  bikeId: string
  onSuccess: () => void
  onCancel: () => void
}

const wearPartTypes = [
  'CHAIN',
  'BRAKE_PADS',
  'TIRE',
  'CASSETTE',
  'CHAINRING',
  'DERAILLEUR',
  'BRAKE_CABLE',
  'SHIFT_CABLE',
  'BRAKE_ROTOR',
  'PEDAL',
  'CRANKSET',
  'BOTTOM_BRACKET',
  'HEADSET',
  'WHEEL',
  'HUB',
  'SPOKE',
  'OTHER',
]

const wearPartStatuses = ['ACTIVE', 'NEEDS_SERVICE', 'REPLACED', 'INACTIVE']

export default function WearPartForm({
  bikeId,
  onSuccess,
  onCancel,
}: WearPartFormProps) {
  const [formData, setFormData] = useState({
    type: 'CHAIN',
    brand: '',
    model: '',
    installDate: new Date().toISOString().split('T')[0],
    installMileage: 0,
    serviceInterval: 1000,
    status: 'ACTIVE',
    cost: '',
    notes: '',
  })
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [isSubmitting, setIsSubmitting] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setErrors({})
    setIsSubmitting(true)

    try {
      const validatedData = wearPartSchema.parse({
        bikeId,
        type: formData.type,
        brand: formData.brand || undefined,
        model: formData.model || undefined,
        installDate: formData.installDate,
        installMileage: Number(formData.installMileage),
        serviceInterval: Number(formData.serviceInterval),
        status: formData.status,
        cost: formData.cost ? Number(formData.cost) : undefined,
        notes: formData.notes || undefined,
      })

      const response = await fetch(`/api/bikes/${bikeId}/parts`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(validatedData),
      })

      if (response.ok) {
        onSuccess()
        setFormData({
          type: 'CHAIN',
          brand: '',
          model: '',
          installDate: new Date().toISOString().split('T')[0],
          installMileage: 0,
          serviceInterval: 1000,
          status: 'ACTIVE',
          cost: '',
          notes: '',
        })
      } else {
        const errorData = await response.json()
        if (errorData.details) {
          const zodErrors: Record<string, string> = {}
          errorData.details.errors?.forEach((err: any) => {
            if (err.path) {
              zodErrors[err.path[0]] = err.message
            }
          })
          setErrors(zodErrors)
        } else {
          alert('Fehler beim Erstellen des Verschleißteils')
        }
      }
    } catch (error: any) {
      if (error.errors) {
        const zodErrors: Record<string, string> = {}
        error.errors.forEach((err: any) => {
          if (err.path) {
            zodErrors[err.path[0]] = err.message
          }
        })
        setErrors(zodErrors)
      } else {
        console.error('Error creating part:', error)
        alert('Fehler beim Erstellen des Verschleißteils')
      }
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="bg-white rounded-lg shadow-md p-6">
      <h2 className="text-2xl font-semibold mb-4">
        Neues Verschleißteil hinzufügen
      </h2>
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Typ *
          </label>
          <select
            value={formData.type}
            onChange={(e) => setFormData({ ...formData, type: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            required
          >
            {wearPartTypes.map((type) => (
              <option key={type} value={type}>
                {type.replace(/_/g, ' ')}
              </option>
            ))}
          </select>
          {errors.type && (
            <p className="text-red-600 text-sm mt-1">{errors.type}</p>
          )}
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Marke
            </label>
            <input
              type="text"
              value={formData.brand}
              onChange={(e) =>
                setFormData({ ...formData, brand: e.target.value })
              }
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Modell
            </label>
            <input
              type="text"
              value={formData.model}
              onChange={(e) =>
                setFormData({ ...formData, model: e.target.value })
              }
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Installationsdatum *
            </label>
            <input
              type="date"
              value={formData.installDate}
              onChange={(e) =>
                setFormData({ ...formData, installDate: e.target.value })
              }
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              required
            />
            {errors.installDate && (
              <p className="text-red-600 text-sm mt-1">{errors.installDate}</p>
            )}
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Installations-KM *
            </label>
            <input
              type="number"
              value={formData.installMileage}
              onChange={(e) =>
                setFormData({
                  ...formData,
                  installMileage: Number(e.target.value),
                })
              }
              min="0"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              required
            />
            {errors.installMileage && (
              <p className="text-red-600 text-sm mt-1">
                {errors.installMileage}
              </p>
            )}
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Service-Intervall (km) *
            </label>
            <input
              type="number"
              value={formData.serviceInterval}
              onChange={(e) =>
                setFormData({
                  ...formData,
                  serviceInterval: Number(e.target.value),
                })
              }
              min="1"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              required
            />
            {errors.serviceInterval && (
              <p className="text-red-600 text-sm mt-1">
                {errors.serviceInterval}
              </p>
            )}
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Status
            </label>
            <select
              value={formData.status}
              onChange={(e) =>
                setFormData({ ...formData, status: e.target.value })
              }
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            >
              {wearPartStatuses.map((status) => (
                <option key={status} value={status}>
                  {status.replace(/_/g, ' ')}
                </option>
              ))}
            </select>
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Kosten (€)
          </label>
          <input
            type="number"
            step="0.01"
            value={formData.cost}
            onChange={(e) =>
              setFormData({ ...formData, cost: e.target.value })
            }
            min="0"
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Notizen
          </label>
          <textarea
            value={formData.notes}
            onChange={(e) =>
              setFormData({ ...formData, notes: e.target.value })
            }
            rows={3}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
        </div>

        <div className="flex gap-2">
          <button
            type="submit"
            disabled={isSubmitting}
            className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
          >
            {isSubmitting ? 'Erstellen...' : 'Erstellen'}
          </button>
          <button
            type="button"
            onClick={onCancel}
            className="px-6 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400 transition-colors"
          >
            Abbrechen
          </button>
        </div>
      </form>
    </div>
  )
}

