import type { FieldConfig } from './fieldConfig'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select'

interface EditableFieldProps {
  field: FieldConfig
  value: unknown
  editable: boolean
  onChange: (key: string, value: unknown) => void
}

function formatDisplayDate(val: string | null | undefined): string {
  if (!val) return '–'
  try {
    return new Date(val).toLocaleDateString('de-DE', {
      day: '2-digit', month: '2-digit', year: 'numeric',
    })
  } catch {
    return val
  }
}

function formatDisplayBoolean(val: unknown): string {
  if (val === true) return 'Ja'
  if (val === false) return 'Nein'
  return '–'
}

function formatDisplayValue(field: FieldConfig, value: unknown): string {
  if (field.type === 'date') return formatDisplayDate(value as string | null)
  if (field.type === 'boolean') return formatDisplayBoolean(value)
  if (field.type === 'select' && field.options) {
    const matchVal = value || '__none__'
    const opt = field.options.find((o) => o.value === matchVal)
    return opt?.label || (value as string) || '–'
  }
  return (value as string) || '–'
}

export function EditableField({ field, value, editable, onChange }: EditableFieldProps) {
  if (!editable) {
    return (
      <div>
        <span className="text-muted-foreground text-sm">{field.label}</span>
        <p className="font-medium text-sm whitespace-pre-wrap">
          {formatDisplayValue(field, value)}
        </p>
      </div>
    )
  }

  const handleChange = (newVal: unknown) => onChange(field.key, newVal)

  return (
    <div>
      <label className="text-sm text-muted-foreground">{field.label}</label>
      <div className="mt-1">
        {field.type === 'text' && (
          <Input
            value={(value as string) ?? ''}
            onChange={(e) => handleChange(e.target.value)}
            placeholder={field.placeholder}
            className="h-8 text-sm"
          />
        )}
        {field.type === 'textarea' && (
          <textarea
            value={(value as string) ?? ''}
            onChange={(e) => handleChange(e.target.value)}
            placeholder={field.placeholder}
            rows={3}
            className="flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-xs placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
          />
        )}
        {field.type === 'date' && (
          <Input
            type="date"
            value={(value as string) ?? ''}
            onChange={(e) => handleChange(e.target.value || null)}
            className="h-8 text-sm"
          />
        )}
        {field.type === 'boolean' && (
          <div className="flex items-center gap-2 h-8">
            <Switch
              checked={value === true}
              onCheckedChange={(checked) => handleChange(checked)}
            />
            <span className="text-sm">{value ? 'Ja' : 'Nein'}</span>
          </div>
        )}
        {field.type === 'select' && field.options && (
          <Select
            value={(value as string) || '__none__'}
            onValueChange={(v) => handleChange(v === '__none__' ? null : v)}
          >
            <SelectTrigger className="h-8 text-sm">
              <SelectValue placeholder="Auswählen..." />
            </SelectTrigger>
            <SelectContent>
              {field.options.map((opt) => (
                <SelectItem key={opt.value} value={opt.value}>
                  {opt.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        )}
      </div>
    </div>
  )
}
