'use client'
// src/components/partners/SecureDeployModal.tsx
// Input: open, partner, onClose
// Output: modal with terminal-style animated deploy logs + RingMeter progress
// Rationale: US18 — Secure Deploy feature, the "wow effect" of the partners screen

import { useEffect, useRef, useState, useCallback } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Loader2, ShieldCheck, CheckCircle2 } from 'lucide-react'
import { Modal } from '@/components/ui/Modal'
import { Button } from '@/components/ui/Button'
import { Select } from '@/components/ui/Select'
import { Badge } from '@/components/ui/Badge'
import { RingMeter } from '@/components/charts/RingMeter'
import { generateDeployLogs } from '@/lib/mock'
import type { DeployLog, Partner } from '@/types'

// ── Constants ─────────────────────────────────────────────────────────────────

const VERSION_OPTIONS = [
  { value: 'v2.5.0', label: 'v2.5.0 — Dernière stable' },
  { value: 'v2.4.1', label: 'v2.4.1 — Maintenance' },
]

// Delay range between log lines (ms)
const LOG_DELAY_MIN = 300
const LOG_DELAY_MAX = 600

// ── Log line color by level ───────────────────────────────────────────────────

const levelColor: Record<DeployLog['level'], string> = {
  success: '#34D399',
  warn: '#FBBF24',
  error: '#F87171',
  info: '#8A9BB0',
}

function formatLogTime(isoTs: string): string {
  try {
    const d = new Date(isoTs)
    const hh = String(d.getUTCHours()).padStart(2, '0')
    const mm = String(d.getUTCMinutes()).padStart(2, '0')
    const ss = String(d.getUTCSeconds()).padStart(2, '00')
    return `${hh}:${mm}:${ss}`
  } catch {
    return '00:00:00'
  }
}

// ── Props ────────────────────────────────────────────────────────────────────

interface SecureDeployModalProps {
  open: boolean
  partner: Partner | null
  onClose: () => void
}

// ── Component ────────────────────────────────────────────────────────────────

export function SecureDeployModal({ open, partner, onClose }: SecureDeployModalProps) {
  const [version, setVersion] = useState('v2.5.0')
  const [includeDemo, setIncludeDemo] = useState(true)
  const [enableMonitoring, setEnableMonitoring] = useState(true)

  const [logs, setLogs] = useState<DeployLog[]>([])
  const [deploying, setDeploying] = useState(false)
  const [done, setDone] = useState(false)
  const [progress, setProgress] = useState(0)

  const terminalRef = useRef<HTMLDivElement>(null)
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  const indexRef = useRef(0)
  const allLogsRef = useRef<DeployLog[]>([])

  // ── Reset state when modal closes ────────────────────────────────────────────

  const resetState = useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current)
      timerRef.current = null
    }
    setLogs([])
    setDeploying(false)
    setDone(false)
    setProgress(0)
    indexRef.current = 0
    allLogsRef.current = []
  }, [])

  useEffect(() => {
    if (!open) {
      resetState()
    }
  }, [open, resetState])

  // ── Auto-scroll terminal to bottom ───────────────────────────────────────────

  useEffect(() => {
    if (terminalRef.current) {
      terminalRef.current.scrollTop = terminalRef.current.scrollHeight
    }
  }, [logs])

  // ── Stream logs one by one with random delay ──────────────────────────────────

  const streamNextLog = useCallback(() => {
    const all = allLogsRef.current
    const idx = indexRef.current

    if (idx >= all.length) {
      // Done
      setDeploying(false)
      setDone(true)
      setProgress(100)
      timerRef.current = null
      return
    }

    // Append log
    setLogs((prev) => [...prev, all[idx]])
    indexRef.current = idx + 1

    // Update progress
    const pct = Math.round(((idx + 1) / all.length) * 100)
    setProgress(pct)

    // Schedule next
    const delay = LOG_DELAY_MIN + Math.random() * (LOG_DELAY_MAX - LOG_DELAY_MIN)
    timerRef.current = setTimeout(streamNextLog, delay)
  }, [])

  // ── Cleanup on unmount ───────────────────────────────────────────────────────

  useEffect(() => {
    return () => {
      if (timerRef.current) clearTimeout(timerRef.current)
    }
  }, [])

  // ── Handlers ──────────────────────────────────────────────────────────────────

  function handleLaunch() {
    if (!partner || deploying || done) return
    const allLogs = generateDeployLogs(partner.name, version, new Date().toISOString())
    allLogsRef.current = allLogs
    indexRef.current = 0
    setLogs([])
    setProgress(0)
    setDeploying(true)
    // Start streaming after a brief initial delay
    timerRef.current = setTimeout(streamNextLog, 200)
  }

  function handleClose() {
    resetState()
    onClose()
  }

  if (!partner) return null

  const ringColor = done
    ? '#34D399'
    : deploying
      ? '#3DB8E8'
      : '#4E6070'

  return (
    <Modal
      open={open}
      onClose={handleClose}
      title={`Secure Deploy → ${partner.name}`}
      size="xl"
    >
      <div className="flex flex-col gap-5">
        {/* Options row */}
        <div className="flex flex-col gap-3">
          {/* Version selector */}
          <div className="flex items-center gap-3">
            <label className="text-label text-text-muted uppercase tracking-[0.05em] shrink-0 w-28">
              Version
            </label>
            <div className="w-64">
              <Select
                options={VERSION_OPTIONS}
                value={version}
                onChange={setVersion}
                placeholder="Sélectionner…"
              />
            </div>
            <Badge variant="accent" size="xs" icon={<ShieldCheck size={10} strokeWidth={1.5} />}>
              Chiffré AES-256
            </Badge>
          </div>

          {/* Checkboxes */}
          <div className="flex items-center gap-6 pl-[7.25rem]">
            <label className="flex items-center gap-2 cursor-pointer select-none group">
              <input
                type="checkbox"
                checked={includeDemo}
                onChange={(e) => setIncludeDemo(e.target.checked)}
                disabled={deploying}
                className="w-3.5 h-3.5 accent-[#3DB8E8] cursor-pointer"
              />
              <span className="text-body text-text-secondary group-hover:text-text-primary transition-colors duration-fast">
                Inclure dataset démo
              </span>
            </label>
            <label className="flex items-center gap-2 cursor-pointer select-none group">
              <input
                type="checkbox"
                checked={enableMonitoring}
                onChange={(e) => setEnableMonitoring(e.target.checked)}
                disabled={deploying}
                className="w-3.5 h-3.5 accent-[#3DB8E8] cursor-pointer"
              />
              <span className="text-body text-text-secondary group-hover:text-text-primary transition-colors duration-fast">
                Activer monitoring
              </span>
            </label>
          </div>
        </div>

        {/* Terminal + RingMeter row */}
        <div className="flex gap-4 items-start">
          {/* Terminal zone */}
          <div
            className="flex-1 bg-bg-base border border-bg-border rounded-lg overflow-hidden"
            style={{ minHeight: 320 }}
          >
            {/* Terminal header bar */}
            <div className="flex items-center gap-1.5 px-3 py-2 border-b border-bg-border bg-bg-elevated">
              <span className="w-2.5 h-2.5 rounded-full bg-status-danger/60" />
              <span className="w-2.5 h-2.5 rounded-full bg-status-warning/60" />
              <span className="w-2.5 h-2.5 rounded-full bg-status-success/60" />
              <span className="ml-2 text-[11px] text-text-muted font-mono">
                structura-deploy — {partner.name}
              </span>
            </div>

            {/* Log output */}
            <div
              ref={terminalRef}
              className="p-3 font-mono text-[11px] leading-[1.6] overflow-y-auto"
              style={{ height: 280 }}
            >
              {logs.length === 0 && !deploying && !done && (
                <span className="text-text-muted">
                  {/* Prompt waiting */}
                  <span className="text-accent">$</span> En attente du lancement…
                </span>
              )}

              <AnimatePresence initial={false}>
                {logs.map((log, i) => (
                  <motion.div
                    key={i}
                    initial={{ opacity: 0, x: -4 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ duration: 0.18, ease: 'easeOut' }}
                    className="flex gap-2 leading-relaxed"
                  >
                    <span className="text-text-muted shrink-0">
                      [{formatLogTime(log.ts)}]
                    </span>
                    <span style={{ color: levelColor[log.level] }}>
                      {log.message}
                    </span>
                  </motion.div>
                ))}
              </AnimatePresence>

              {/* Blinking cursor when deploying */}
              {deploying && (
                <span className="inline-block w-1.5 h-3.5 bg-accent ml-1 animate-pulse align-middle" />
              )}

              {/* Final success line */}
              {done && (
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  transition={{ delay: 0.2 }}
                  className="flex items-center gap-2 mt-1"
                >
                  <CheckCircle2 size={12} strokeWidth={1.5} style={{ color: '#34D399' }} />
                  <span style={{ color: '#34D399' }} className="font-semibold">
                    Déploiement terminé — build chiffré transmis avec succès.
                  </span>
                </motion.div>
              )}
            </div>
          </div>

          {/* RingMeter progress */}
          <div className="flex flex-col items-center gap-2 pt-10 shrink-0">
            <RingMeter
              value={progress}
              max={100}
              label={done ? 'terminé' : deploying ? 'en cours' : 'prêt'}
              color={ringColor}
              size={88}
              strokeWidth={6}
            />
            <span className="text-caption text-text-muted">Progression</span>
          </div>
        </div>

        {/* Footer actions */}
        <div className="flex items-center justify-end gap-3 pt-1 border-t border-bg-border">
          {!deploying && !done && (
            <>
              <Button variant="ghost" onClick={handleClose}>
                Annuler
              </Button>
              <Button
                variant="primary"
                iconLeft={<ShieldCheck size={16} strokeWidth={1.5} />}
                onClick={handleLaunch}
              >
                Lancer le déploiement
              </Button>
            </>
          )}

          {deploying && (
            <div className="flex items-center gap-2 text-text-secondary text-body">
              <Loader2 size={15} strokeWidth={1.5} className="animate-spin text-accent" />
              <span>Déploiement en cours…</span>
            </div>
          )}

          {done && (
            <Button
              variant="primary"
              iconLeft={<CheckCircle2 size={16} strokeWidth={1.5} />}
              onClick={handleClose}
            >
              Fermer
            </Button>
          )}
        </div>
      </div>
    </Modal>
  )
}
