'use client'

import React, { useState } from 'react'
import { useSDK } from '@/lib/sdk'
import type { ProjectInfo, CustomerType } from '@/lib/sdk/types'

/** Map snake_case backend response to camelCase ProjectInfo */
export function normalizeProject(p: any): ProjectInfo {
  return {
    id: p.id,
    name: p.name,
    description: p.description || '',
    customerType: p.customerType || p.customer_type || 'new',
    status: p.status || 'active',
    projectVersion: p.projectVersion ?? p.project_version ?? 1,
    completionPercentage: p.completionPercentage ?? p.completion_percentage ?? 0,
    createdAt: p.createdAt || p.created_at || '',
    updatedAt: p.updatedAt || p.updated_at || '',
  }
}

interface CreateProjectDialogProps {
  open: boolean
  onClose: () => void
  onCreated: (project: ProjectInfo) => void
  existingProjects: ProjectInfo[]
}

export function CreateProjectDialog({ open, onClose, onCreated, existingProjects }: CreateProjectDialogProps) {
  const { createProject } = useSDK()
  const [name, setName] = useState('')
  const [customerType, setCustomerType] = useState<CustomerType>('new')
  const [copyFromId, setCopyFromId] = useState<string>('')
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState('')

  if (!open) return null

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!name.trim()) {
      setError('Projektname ist erforderlich')
      return
    }

    setIsSubmitting(true)
    setError('')
    try {
      const project = await createProject(
        name.trim(),
        customerType,
        copyFromId || undefined
      )
      onCreated(normalizeProject(project))
      setName('')
      setCopyFromId('')
      onClose()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Fehler beim Erstellen des Projekts')
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={onClose}>
      <div
        className="bg-white rounded-2xl shadow-xl w-full max-w-lg mx-4 p-6"
        onClick={e => e.stopPropagation()}
      >
        <h2 className="text-xl font-bold text-gray-900 mb-6">Neues Projekt erstellen</h2>

        <form onSubmit={handleSubmit} className="space-y-5">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Projektname *
            </label>
            <input
              type="text"
              value={name}
              onChange={e => setName(e.target.value)}
              placeholder="z.B. KI-Produkt X, SaaS API, Tochter GmbH..."
              className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 outline-none"
              autoFocus
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Projekttyp
            </label>
            <div className="grid grid-cols-2 gap-3">
              <button
                type="button"
                onClick={() => setCustomerType('new')}
                className={`p-3 rounded-lg border-2 text-left transition-all ${
                  customerType === 'new'
                    ? 'border-purple-500 bg-purple-50'
                    : 'border-gray-200 hover:border-gray-300'
                }`}
              >
                <div className="font-medium text-sm text-gray-900">Neukunde</div>
                <div className="text-xs text-gray-500 mt-0.5">Compliance von Grund auf</div>
              </button>
              <button
                type="button"
                onClick={() => setCustomerType('existing')}
                className={`p-3 rounded-lg border-2 text-left transition-all ${
                  customerType === 'existing'
                    ? 'border-purple-500 bg-purple-50'
                    : 'border-gray-200 hover:border-gray-300'
                }`}
              >
                <div className="font-medium text-sm text-gray-900">Bestandskunde</div>
                <div className="text-xs text-gray-500 mt-0.5">Bestehende Dokumente erweitern</div>
              </button>
            </div>
          </div>

          {existingProjects.length > 0 && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Stammdaten kopieren von (optional)
              </label>
              <select
                value={copyFromId}
                onChange={e => setCopyFromId(e.target.value)}
                className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 outline-none bg-white"
              >
                <option value="">— Keine Kopie (leeres Projekt) —</option>
                {existingProjects.map(p => (
                  <option key={p.id} value={p.id}>
                    {p.name} (V{String(p.projectVersion).padStart(3, '0')})
                  </option>
                ))}
              </select>
              <p className="mt-1 text-xs text-gray-500">
                Firmenprofil wird kopiert und kann dann unabhaengig bearbeitet werden.
              </p>
            </div>
          )}

          {error && (
            <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
              {error}
            </div>
          )}

          <div className="flex gap-3 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
            >
              Abbrechen
            </button>
            <button
              type="submit"
              disabled={isSubmitting || !name.trim()}
              className="flex-1 px-4 py-2.5 text-sm font-medium text-white bg-purple-600 hover:bg-purple-700 disabled:bg-purple-300 rounded-lg transition-colors"
            >
              {isSubmitting ? 'Erstelle...' : 'Projekt erstellen'}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
