'use client'

import { useState, useEffect, useCallback } from 'react'
import Link from 'next/link'

interface VariantProject {
  id: string
  machine_name: string
  description?: string
  status: string
  hazard_count?: number
  parent_project_id?: string
}

interface VariantGapResponse {
  base_project: { id: string; name: string; hazard_count: number; measure_count: number }
  variant: { id: string; name: string; hazard_count: number; measure_count: number }
  gap: { additional_hazards: number; additional_measures: number; categories_affected: string[] }
}

interface Props {
  projectId: string
  parentProjectId?: string | null
  parentProjectName?: string
}

export function VariantPanel({ projectId, parentProjectId, parentProjectName }: Props) {
  const [variants, setVariants] = useState<VariantProject[]>([])
  const [gapMap, setGapMap] = useState<Record<string, VariantGapResponse>>({})
  const [loading, setLoading] = useState(true)
  const [showCreate, setShowCreate] = useState(false)
  const [creating, setCreating] = useState(false)
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')

  const fetchVariants = useCallback(async () => {
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/variants`)
      if (!res.ok) {
        setVariants([])
        return
      }
      const json = await res.json()
      const list: VariantProject[] = json.variants || json.projects || []
      setVariants(list)

      // Fetch gap analysis for this project
      const gapRes = await fetch(`/api/sdk/v1/iace/projects/${projectId}/variant-gap`)
      if (gapRes.ok) {
        const gapJson = await gapRes.json()
        const gaps: Record<string, VariantGapResponse> = {}
        // Could be a single gap or array — handle both
        if (Array.isArray(gapJson)) {
          for (const g of gapJson) {
            gaps[g.variant?.id] = g
          }
        } else if (gapJson.variant) {
          gaps[gapJson.variant.id] = gapJson
        }
        setGapMap(gaps)
      }
    } catch {
      setVariants([])
    } finally {
      setLoading(false)
    }
  }, [projectId])

  useEffect(() => {
    fetchVariants()
  }, [fetchVariants])

  async function handleCreate() {
    if (!name.trim()) return
    setCreating(true)
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/variants`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          machine_name: name.trim(),
          description: description.trim(),
        }),
      })
      if (res.ok) {
        setName('')
        setDescription('')
        setShowCreate(false)
        fetchVariants()
      }
    } catch {
      // silently handle
    } finally {
      setCreating(false)
    }
  }

  // If this project IS a variant, show link to base project
  if (parentProjectId) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-purple-200 dark:border-purple-700 p-6">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 bg-purple-50 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
            <svg className="w-5 h-5 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" />
            </svg>
          </div>
          <div className="flex-1">
            <p className="text-sm font-semibold text-gray-900 dark:text-white">Variante</p>
            <p className="text-xs text-gray-500">
              Dieses Projekt ist eine Variante des Basis-Projekts
            </p>
          </div>
          <Link
            href={`/sdk/iace/${parentProjectId}`}
            className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-purple-700 bg-purple-50 rounded-lg hover:bg-purple-100 dark:text-purple-300 dark:bg-purple-900/30 dark:hover:bg-purple-900/50 transition-colors"
          >
            {parentProjectName || 'Basis-Projekt'}
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />
            </svg>
          </Link>
        </div>
      </div>
    )
  }

  if (loading) return null
  if (variants.length === 0 && !showCreate) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-gray-50 dark:bg-gray-700 rounded-lg flex items-center justify-center">
              <svg className="w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
              </svg>
            </div>
            <div>
              <p className="text-sm font-semibold text-gray-900 dark:text-white">Keine Varianten</p>
              <p className="text-xs text-gray-500">Erstellen Sie Varianten fuer verschiedene Betriebsarten</p>
            </div>
          </div>
          <button
            onClick={() => setShowCreate(true)}
            className="px-3 py-1.5 text-sm font-medium text-purple-700 bg-purple-50 rounded-lg hover:bg-purple-100 dark:text-purple-300 dark:bg-purple-900/30 dark:hover:bg-purple-900/50 transition-colors"
          >
            + Neue Variante
          </button>
        </div>
        {renderCreateDialog()}
      </div>
    )
  }

  function renderCreateDialog() {
    if (!showCreate) return null
    return (
      <div className="mt-4 p-4 border border-purple-200 dark:border-purple-700 rounded-lg bg-purple-50/50 dark:bg-purple-900/10 space-y-3">
        <h3 className="text-sm font-semibold text-gray-900 dark:text-white">Neue Variante erstellen</h3>
        <input
          type="text"
          placeholder="Variantenname (z.B. Kollaborierender Betrieb)"
          value={name}
          onChange={(e) => setName(e.target.value)}
          className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg bg-white dark:bg-gray-800 dark:border-gray-600 dark:text-white focus:ring-2 focus:ring-purple-500 focus:border-transparent"
        />
        <textarea
          placeholder="Beschreibung (optional)"
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          rows={2}
          className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg bg-white dark:bg-gray-800 dark:border-gray-600 dark:text-white focus:ring-2 focus:ring-purple-500 focus:border-transparent"
        />
        <div className="flex gap-2 justify-end">
          <button
            onClick={() => { setShowCreate(false); setName(''); setDescription('') }}
            className="px-3 py-1.5 text-sm text-gray-600 hover:text-gray-800 dark:text-gray-400"
          >
            Abbrechen
          </button>
          <button
            onClick={handleCreate}
            disabled={creating || !name.trim()}
            className="px-4 py-1.5 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors"
          >
            {creating ? 'Erstelle...' : 'Erstellen'}
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 bg-purple-50 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
            <svg className="w-5 h-5 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
            </svg>
          </div>
          <div>
            <h2 className="text-sm font-semibold text-gray-900 dark:text-white">
              Varianten ({variants.length})
            </h2>
            <p className="text-xs text-gray-500">Betriebsart-spezifische Projektversionen</p>
          </div>
        </div>
        <button
          onClick={() => setShowCreate(true)}
          className="px-3 py-1.5 text-sm font-medium text-purple-700 bg-purple-50 rounded-lg hover:bg-purple-100 dark:text-purple-300 dark:bg-purple-900/30 dark:hover:bg-purple-900/50 transition-colors"
        >
          + Neue Variante
        </button>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        {variants.map((v) => {
          const gap = gapMap[v.id]
          return (
            <Link
              key={v.id}
              href={`/sdk/iace/${v.id}`}
              className="block p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:shadow-md hover:border-purple-300 transition-all group"
            >
              <div className="flex items-start justify-between gap-2">
                <div className="min-w-0 flex-1">
                  <p className="text-sm font-medium text-gray-900 dark:text-white truncate group-hover:text-purple-700 dark:group-hover:text-purple-400">
                    {v.machine_name}
                  </p>
                  {v.description && (
                    <p className="text-xs text-gray-500 mt-0.5 line-clamp-2">{v.description}</p>
                  )}
                </div>
                <svg className="w-4 h-4 text-gray-400 group-hover:text-purple-600 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />
                </svg>
              </div>
              {gap && gap.gap.additional_hazards > 0 && (
                <span className="inline-flex items-center mt-2 px-2 py-0.5 text-xs font-medium bg-orange-100 text-orange-800 dark:bg-orange-900/50 dark:text-orange-300 rounded-full">
                  +{gap.gap.additional_hazards} Gefaehrdungen
                </span>
              )}
            </Link>
          )
        })}
      </div>

      {renderCreateDialog()}
    </div>
  )
}
