'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { PagePurpose } from '@/components/common/PagePurpose'

// Types
interface FundingApplication {
  id: string
  application_number: string
  title: string
  funding_program: string
  status: string
  current_step: number
  total_steps: number
  requested_amount: number
  school_profile?: {
    name: string
    federal_state: string
  }
  created_at: string
  updated_at: string
}

interface Statistics {
  total_applications: number
  draft_count: number
  submitted_count: number
  approved_count: number
  total_requested: number
  total_approved: number
}

const API_BASE = process.env.NEXT_PUBLIC_SDK_API_URL || 'http://localhost:8080'

// Status badge colors
const statusColors: Record<string, { bg: string; text: string; label: string }> = {
  DRAFT: { bg: 'bg-slate-100', text: 'text-slate-700', label: 'Entwurf' },
  IN_PROGRESS: { bg: 'bg-blue-100', text: 'text-blue-700', label: 'In Bearbeitung' },
  REVIEW: { bg: 'bg-amber-100', text: 'text-amber-700', label: 'Pruefung' },
  SUBMITTED: { bg: 'bg-purple-100', text: 'text-purple-700', label: 'Eingereicht' },
  APPROVED: { bg: 'bg-green-100', text: 'text-green-700', label: 'Genehmigt' },
  REJECTED: { bg: 'bg-red-100', text: 'text-red-700', label: 'Abgelehnt' },
}

const programLabels: Record<string, string> = {
  DIGITALPAKT_1: 'DigitalPakt 1.0',
  DIGITALPAKT_2: 'DigitalPakt 2.0',
  LANDESFOERDERUNG: 'Landesfoerderung',
  SCHULTRAEGER: 'Schultraeger',
}

export default function FoerderantragPage() {
  const [applications, setApplications] = useState<FundingApplication[]>([])
  const [statistics, setStatistics] = useState<Statistics | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

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

  const loadData = async () => {
    try {
      setLoading(true)
      // In production, these would be real API calls
      // For now, we use mock data
      setApplications([])
      setStatistics({
        total_applications: 0,
        draft_count: 0,
        submitted_count: 0,
        approved_count: 0,
        total_requested: 0,
        total_approved: 0,
      })
    } catch (err) {
      setError('Fehler beim Laden der Daten')
    } finally {
      setLoading(false)
    }
  }

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('de-DE', {
      style: 'currency',
      currency: 'EUR',
    }).format(amount)
  }

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('de-DE', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    })
  }

  return (
    <div className="space-y-8">
      {/* Page Purpose */}
      <PagePurpose
        title="Foerderantrag-Wizard"
        purpose="Erstellen Sie antragsfaehige Foerderantraege fuer Schulen. Der Wizard fuehrt Sie Schritt fuer Schritt durch den Prozess und generiert alle erforderlichen Dokumente."
        audience={['Schulleitung', 'IT-Beauftragte', 'Schultraeger']}
        architecture={{
          services: ['ai-compliance-sdk (Go)', 'LLM-Service (32B)'],
          databases: ['PostgreSQL'],
        }}
        collapsible={true}
        defaultCollapsed={true}
      />

      {/* Hero Section */}
      <div className="relative overflow-hidden rounded-2xl bg-gradient-to-br from-blue-600 via-blue-700 to-indigo-800 p-8 text-white">
        <div className="absolute inset-0 bg-[url('/grid-pattern.svg')] opacity-10" />
        <div className="relative z-10">
          <div className="flex items-start justify-between">
            <div>
              <h1 className="text-3xl font-bold">Foerderantrag-Wizard</h1>
              <p className="mt-2 text-blue-100 max-w-2xl">
                Erstellen Sie vollstaendige Foerderantraege fuer DigitalPakt 2.0 und Landesfoerderungen.
                Der Wizard fuehrt Sie durch alle 8 Schritte und generiert antragsfaehige Dokumente.
              </p>
              <div className="mt-6 flex gap-4">
                <Link
                  href="/education/foerderantrag/new"
                  className="inline-flex items-center gap-2 px-6 py-3 bg-white text-blue-700 rounded-xl font-semibold hover:bg-blue-50 transition-colors shadow-lg"
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                  </svg>
                  Neuen Antrag starten
                </Link>
              </div>
            </div>
            <div className="hidden lg:block">
              <svg className="w-32 h-32 text-blue-300 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
            </div>
          </div>
        </div>
      </div>

      {/* Statistics Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border border-slate-200 p-5 hover:shadow-md transition-shadow">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-blue-100 flex items-center justify-center">
              <svg className="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
            </div>
            <div>
              <div className="text-2xl font-bold text-slate-900">{statistics?.total_applications || 0}</div>
              <div className="text-sm text-slate-500">Antraege gesamt</div>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl border border-slate-200 p-5 hover:shadow-md transition-shadow">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-amber-100 flex items-center justify-center">
              <svg className="w-6 h-6 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
              </svg>
            </div>
            <div>
              <div className="text-2xl font-bold text-slate-900">{statistics?.draft_count || 0}</div>
              <div className="text-sm text-slate-500">Entwuerfe</div>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl border border-slate-200 p-5 hover:shadow-md transition-shadow">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-purple-100 flex items-center justify-center">
              <svg className="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
              </svg>
            </div>
            <div>
              <div className="text-2xl font-bold text-slate-900">{statistics?.submitted_count || 0}</div>
              <div className="text-sm text-slate-500">Eingereicht</div>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl border border-slate-200 p-5 hover:shadow-md transition-shadow">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-green-100 flex items-center justify-center">
              <svg className="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <div>
              <div className="text-2xl font-bold text-slate-900">{formatCurrency(statistics?.total_requested || 0)}</div>
              <div className="text-sm text-slate-500">Beantragt</div>
            </div>
          </div>
        </div>
      </div>

      {/* Quick Start Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <Link
          href="/education/foerderantrag/new?preset=breakpilot_basic"
          className="group bg-white rounded-xl border-2 border-slate-200 p-6 hover:border-blue-400 hover:shadow-lg transition-all"
        >
          <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center mb-4">
            <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
            </svg>
          </div>
          <h3 className="font-semibold text-lg text-slate-900 group-hover:text-blue-600 transition-colors">
            BreakPilot Basis
          </h3>
          <p className="text-sm text-slate-500 mt-1">
            Lokale KI-Arbeitsstation fuer eine Schule. Vorausgefuellte Kostenplanung und Datenschutzkonzept.
          </p>
          <div className="mt-4 text-sm font-medium text-blue-600">
            ~18.500 EUR Foerdervolumen
          </div>
        </Link>

        <Link
          href="/education/foerderantrag/new?preset=breakpilot_cluster"
          className="group bg-white rounded-xl border-2 border-slate-200 p-6 hover:border-blue-400 hover:shadow-lg transition-all"
        >
          <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-purple-500 to-pink-600 flex items-center justify-center mb-4">
            <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
            </svg>
          </div>
          <h3 className="font-semibold text-lg text-slate-900 group-hover:text-purple-600 transition-colors">
            BreakPilot Schulverbund
          </h3>
          <p className="text-sm text-slate-500 mt-1">
            Zentrale KI-Infrastruktur fuer mehrere Schulen eines Traegers.
          </p>
          <div className="mt-4 text-sm font-medium text-purple-600">
            ~68.500 EUR Foerdervolumen
          </div>
        </Link>

        <Link
          href="/education/foerderantrag/new"
          className="group bg-white rounded-xl border-2 border-slate-200 p-6 hover:border-slate-400 hover:shadow-lg transition-all"
        >
          <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-slate-500 to-slate-700 flex items-center justify-center mb-4">
            <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4" />
            </svg>
          </div>
          <h3 className="font-semibold text-lg text-slate-900 group-hover:text-slate-700 transition-colors">
            Individueller Antrag
          </h3>
          <p className="text-sm text-slate-500 mt-1">
            Leerer Wizard fuer individuelle Projekte. Volle Flexibilitaet bei der Planung.
          </p>
          <div className="mt-4 text-sm font-medium text-slate-600">
            Beliebiges Foerdervolumen
          </div>
        </Link>
      </div>

      {/* Applications List */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-200 flex items-center justify-between">
          <h2 className="font-semibold text-lg text-slate-900">Meine Antraege</h2>
          <div className="flex items-center gap-2">
            <select className="px-3 py-1.5 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
              <option value="">Alle Status</option>
              <option value="DRAFT">Entwurf</option>
              <option value="SUBMITTED">Eingereicht</option>
              <option value="APPROVED">Genehmigt</option>
            </select>
          </div>
        </div>

        {loading ? (
          <div className="p-12 text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-4 text-slate-500">Lade Antraege...</p>
          </div>
        ) : applications.length === 0 ? (
          <div className="p-12 text-center">
            <svg className="w-16 h-16 text-slate-300 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
            <h3 className="mt-4 text-lg font-medium text-slate-900">Noch keine Antraege</h3>
            <p className="mt-2 text-slate-500">
              Starten Sie jetzt Ihren ersten Foerderantrag mit dem Wizard.
            </p>
            <Link
              href="/education/foerderantrag/new"
              className="mt-6 inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
              </svg>
              Ersten Antrag erstellen
            </Link>
          </div>
        ) : (
          <div className="divide-y divide-slate-100">
            {applications.map((app) => {
              const status = statusColors[app.status] || statusColors.DRAFT
              return (
                <Link
                  key={app.id}
                  href={`/education/foerderantrag/${app.id}`}
                  className="flex items-center gap-4 p-4 hover:bg-slate-50 transition-colors"
                >
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-3">
                      <h3 className="font-medium text-slate-900 truncate">{app.title}</h3>
                      <span className={`px-2 py-0.5 text-xs font-medium rounded-full ${status.bg} ${status.text}`}>
                        {status.label}
                      </span>
                    </div>
                    <div className="flex items-center gap-4 mt-1 text-sm text-slate-500">
                      <span>{app.application_number}</span>
                      <span>{programLabels[app.funding_program] || app.funding_program}</span>
                      {app.school_profile?.name && (
                        <span>{app.school_profile.name}</span>
                      )}
                    </div>
                  </div>
                  <div className="text-right">
                    <div className="font-medium text-slate-900">{formatCurrency(app.requested_amount)}</div>
                    <div className="text-sm text-slate-500">Schritt {app.current_step}/{app.total_steps}</div>
                  </div>
                  <svg className="w-5 h-5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                </Link>
              )
            })}
          </div>
        )}
      </div>

      {/* Info Box */}
      <div className="bg-blue-50 border border-blue-200 rounded-xl p-6">
        <div className="flex gap-4">
          <div className="flex-shrink-0">
            <svg className="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
          <div>
            <h3 className="font-semibold text-blue-800">Wichtiger Hinweis</h3>
            <p className="mt-1 text-sm text-blue-700">
              Der Wizard erstellt einen <strong>antragsfaehigen Entwurf</strong>. Die finale Pruefung und
              Einreichung erfolgt durch den Schultraeger. Alle generierten Dokumente (Antragsschreiben,
              Kostenplan, Datenschutzkonzept) koennen als ZIP heruntergeladen werden.
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}
