'use client'

import { useEffect, useRef, useState } from 'react'
import Navbar from '@/components/layout/Navbar'
import Footer from '@/components/layout/Footer'
import ChatFAB from '@/components/layout/ChatFAB'
import PageHeader from '@/components/ui/PageHeader'
import GlassCard from '@/components/ui/GlassCard'
import FadeInView from '@/components/ui/FadeInView'
import { Cookie, ShieldCheck, Mail, ArrowRight, CheckCircle2, AlertTriangle } from 'lucide-react'

export default function SavingsScanPage() {
  const [url, setUrl] = useState('')
  const [email, setEmail] = useState('')
  const [consent, setConsent] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [done, setDone] = useState(false)
  const [checkId, setCheckId] = useState<string | null>(null)
  const [progress, setProgress] = useState<string>('')
  const [progressPct, setProgressPct] = useState<number>(0)
  const [error, setError] = useState<string | null>(null)
  const pollingRef = useRef<boolean>(false)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!url || !email) return
    setError(null)
    setSubmitting(true)
    try {
      const res = await fetch('/api/scan/start', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ url, email, consent }),
      })
      const data = await res.json()
      if (!res.ok) {
        setError(data.detail || data.error || 'Scan konnte nicht gestartet werden')
        return
      }
      setCheckId(data.check_id)
      setDone(true)
    } catch {
      setError('Netzwerkfehler — bitte erneut versuchen.')
    } finally {
      setSubmitting(false)
    }
  }

  useEffect(() => {
    if (!checkId || pollingRef.current) return
    pollingRef.current = true
    let cancelled = false
    const poll = async () => {
      for (let i = 0; i < 60 && !cancelled; i++) {
        await new Promise(r => setTimeout(r, 5000))
        try {
          const res = await fetch(`/api/scan/status/${checkId}`)
          const data = await res.json()
          if (data.progress) setProgress(data.progress)
          if (typeof data.progress_pct === 'number') setProgressPct(data.progress_pct)
          if (['completed', 'failed', 'skipped_tdm'].includes(data.status)) {
            if (data.status !== 'completed') {
              setError(data.error || 'Scan abgebrochen')
            }
            return
          }
        } catch { /* retry */ }
      }
    }
    poll()
    return () => { cancelled = true; pollingRef.current = false }
  }, [checkId])

  return (
    <>
      <Navbar />
      <main>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <PageHeader
            tag="KOSTENLOSER SAVING-SCAN"
            title="In 5 Minuten zur"
            titleHighlight="sechsstelligen Saving-Schaetzung"
            subtitle="URL eingeben — wir analysieren alle Cookies, identifizieren redundante Anbieter und schaetzen jaehrliche Einsparung. Kostenlos, ohne Login, ohne Vertrieb-Termin."
          />
        </div>

        <section className="py-12 sm:py-16">
          <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8">
            {!done ? (
              <GlassCard>
                <form onSubmit={handleSubmit} className="space-y-5">
                  <div>
                    <label htmlFor="url" className="block text-sm font-medium text-white/70 mb-2">
                      Website-URL <span className="text-red-400">*</span>
                    </label>
                    <input
                      id="url"
                      type="url"
                      required
                      placeholder="https://www.ihre-firma.de"
                      value={url}
                      onChange={e => setUrl(e.target.value)}
                      className="w-full px-4 py-3 rounded-lg bg-white/[0.04] border border-white/10
                                 text-white placeholder-white/30 focus:border-emerald-400 focus:outline-none"
                    />
                    <p className="mt-1 text-xs text-white/40">
                      Wir crawlen die Startseite + automatisch erkennbare Unterseiten
                      (DSI, Impressum, Cookie-Richtlinie).
                    </p>
                  </div>

                  <div>
                    <label htmlFor="email" className="block text-sm font-medium text-white/70 mb-2">
                      E-Mail fuer den Bericht <span className="text-red-400">*</span>
                    </label>
                    <input
                      id="email"
                      type="email"
                      required
                      placeholder="ihr.name@firma.de"
                      value={email}
                      onChange={e => setEmail(e.target.value)}
                      className="w-full px-4 py-3 rounded-lg bg-white/[0.04] border border-white/10
                                 text-white placeholder-white/30 focus:border-emerald-400 focus:outline-none"
                    />
                    <p className="mt-1 text-xs text-white/40">
                      Bericht kommt als PDF + JSON. Die Mailadresse wird ausschliesslich
                      fuer diesen Scan verwendet.
                    </p>
                  </div>

                  <label className="flex items-start gap-2 text-xs text-white/60 cursor-pointer">
                    <input type="checkbox" checked={consent} onChange={e => setConsent(e.target.checked)}
                      className="mt-0.5 accent-emerald-500" />
                    <span>
                      Ich stimme zu, dass meine E-Mail fuer den Saving-Report + ein
                      einmaliges Sales-Follow-Up genutzt wird. Widerruf jederzeit per E-Mail.
                    </span>
                  </label>

                  {error && (
                    <p className="text-sm text-amber-300/80 bg-amber-500/10 border border-amber-400/30 rounded px-3 py-2">
                      {error}
                    </p>
                  )}

                  <button
                    type="submit"
                    disabled={submitting || !consent}
                    className="inline-flex items-center gap-2 px-6 py-3 rounded-full
                               bg-emerald-500 hover:bg-emerald-400 transition-colors
                               text-enterprise-dark font-semibold disabled:opacity-50"
                  >
                    {submitting ? 'Wird gestartet …' : 'Saving-Scan starten'}
                    <ArrowRight className="w-4 h-4" />
                  </button>

                  <p className="text-xs text-white/40 pt-2">
                    Wir analysieren ausschliesslich oeffentlich abrufbare Daten Ihrer Website
                    unter Beachtung maschinenlesbarer Nutzungsvorbehalte (§ 44b UrhG).
                    Pro Domain max. 1 Scan / 24h. Ergebnis innerhalb von ~3-5 Minuten per E-Mail.
                  </p>
                </form>
              </GlassCard>
            ) : (
              <GlassCard>
                <div className="text-center py-6">
                  {error ? (
                    <AlertTriangle className="w-12 h-12 text-amber-400 mx-auto mb-4" />
                  ) : (
                    <CheckCircle2 className="w-12 h-12 text-emerald-400 mx-auto mb-4" />
                  )}
                  <h3 className="text-xl font-bold mb-2">
                    {error ? 'Scan-Hinweis' : (progressPct >= 100 ? 'Scan abgeschlossen' : 'Scan laeuft')}
                  </h3>
                  {error ? (
                    <p className="text-amber-300/80 mb-4 text-sm">{error}</p>
                  ) : (
                    <>
                      <p className="text-white/60 mb-4">
                        {progressPct >= 100
                          ? <>Der Bericht ist unterwegs an <strong className="text-white/90">{email}</strong>.</>
                          : <>Wir analysieren <strong className="text-white/90">{url}</strong>. Bericht kommt in ~3-5 Min an <strong className="text-white/90">{email}</strong>.</>
                        }
                      </p>
                      {progress && progressPct < 100 && (
                        <div className="max-w-md mx-auto mt-4">
                          <div className="text-xs text-white/50 mb-2">{progress}</div>
                          <div className="w-full bg-white/10 rounded-full h-2 overflow-hidden">
                            <div className="bg-emerald-400 h-full transition-all" style={{ width: `${progressPct}%` }} />
                          </div>
                          <div className="text-xs text-white/40 mt-1">{progressPct}%</div>
                        </div>
                      )}
                      <p className="text-xs text-white/40 mt-4">
                        Pruefen Sie auch Ihren Spam-Ordner.
                      </p>
                    </>
                  )}
                </div>
              </GlassCard>
            )}
          </div>
        </section>

        <section className="py-16">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <FadeInView>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <GlassCard>
                  <Cookie className="w-8 h-8 text-emerald-400 mb-4" />
                  <h3 className="text-lg font-bold mb-2">Was wir analysieren</h3>
                  <ul className="text-sm text-white/60 space-y-2">
                    <li>• Alle Cookies + Vendor-Identifikation</li>
                    <li>• Funktionale Kategorisierung (Analytics, Werbung, CDN, …)</li>
                    <li>• Redundanz-Detection ueber Kategorien</li>
                    <li>• Cookie-Tiefenanalyse mit Tier-Inferenz</li>
                  </ul>
                </GlassCard>
                <GlassCard delay={0.1}>
                  <ShieldCheck className="w-8 h-8 text-emerald-400 mb-4" />
                  <h3 className="text-lg font-bold mb-2">Was Sie bekommen</h3>
                  <ul className="text-sm text-white/60 space-y-2">
                    <li>• Geschaetzte jaehrliche Tooling-Kosten (Listpreis-Range)</li>
                    <li>• Sparpotenzial pro Konsolidierungs-Kandidat</li>
                    <li>• EU-Alternative pro US-Vendor</li>
                    <li>• Schrems-II-Risiko-Bewertung</li>
                  </ul>
                </GlassCard>
                <GlassCard delay={0.2}>
                  <Mail className="w-8 h-8 text-emerald-400 mb-4" />
                  <h3 className="text-lg font-bold mb-2">Was es kostet</h3>
                  <ul className="text-sm text-white/60 space-y-2">
                    <li>• <strong className="text-white">Erster Scan: kostenlos</strong></li>
                    <li>• Kein Login, kein Vertriebs-Termin</li>
                    <li>• Daten werden nicht gespeichert</li>
                    <li>• PDF + JSON zum Download</li>
                  </ul>
                </GlassCard>
              </div>
            </FadeInView>
          </div>
        </section>
      </main>
      <Footer />
      <ChatFAB />
    </>
  )
}
