'use client'

import { useCallback, useEffect, useState } from 'react'
import {
  getControlPrompt,
  getPromptHistory,
  listPlatformBusinesses,
  PlatformBusiness,
  setControlPrompt,
  setLandingContent,
  ControlPrompt,
  getSystemStatus,
  LandingContent,
} from '@/lib/api/platform'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card'
import { Skeleton } from '@/components/ui/Skeleton'
import { ErrorState } from '@/components/ui/ErrorState'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { useToast } from '@/components/ui/Toast'
import { FileText, History, PenLine } from 'lucide-react'

const LANDING_FIELDS: Array<{
  key: 'badge' | 'title' | 'subtitle' | 'cta_primary' | 'cta_secondary' | 'demo_hint' | 'footer_note'
  label: string
  hint: string
}> = [
  { key: 'badge', label: 'Hero badge', hint: 'Small pill above the headline, e.g. "Autonomous business operations"' },
  { key: 'title', label: 'Headline', hint: 'Main landing headline' },
  { key: 'subtitle', label: 'Subtitle', hint: 'Supporting paragraph under the headline' },
  { key: 'cta_primary', label: 'Primary CTA label', hint: 'Main button text (Start Managing Operations)' },
  { key: 'cta_secondary', label: 'Secondary CTA label', hint: 'Outline button text (See How It Works)' },
  { key: 'demo_hint', label: 'Demo hint', hint: 'Small line shown under the buttons to demo visitors' },
  { key: 'footer_note', label: 'Footer note', hint: 'Text shown in the page footer' },
]

export default function PromptAndLandingPage() {
  const { toast } = useToast()
  const [prompt, setPrompt] = useState<ControlPrompt | null>(null)
  const [promptText, setPromptText] = useState('')
  const [history, setHistory] = useState<Array<{ version: number; instruction: string; changed_at: string | null }>>([])
  const [businesses, setBusinesses] = useState<PlatformBusiness[]>([])
  const [bizId, setBizId] = useState('')
  const [bizPrompt, setBizPrompt] = useState('')
  const [landing, setLanding] = useState<LandingContent>({})
  const [error, setError] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)
  const [saved, setSaved] = useState<{ where: string; version: number } | null>(null)

  const load = useCallback(async () => {
    setError(null)
    const [p, h, b, s] = await Promise.all([
      getControlPrompt(),
      getPromptHistory(),
      listPlatformBusinesses('active'),
      getSystemStatus(),
    ])
    if (p.success) {
      setPrompt(p.data)
      setPromptText(p.data?.instruction ?? '')
    } else setError(p.message)
    if (h.success) setHistory(h.data.history)
    if (b.success) setBusinesses(b.data.businesses)
    if (s.success && s.data.master_prompt) {
      setBizPrompt(s.data.master_prompt.instruction)
    }
  }, [])

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

  const handleSaveMaster = async () => {
    setBusy(true)
    const res = await setControlPrompt(promptText)
    setBusy(false)
    if (res.success) {
      setSaved({ where: 'master', version: res.data.version })
      load()
      toast({ title: 'Master prompt updated', description: `Now version ${res.data.version}`, variant: 'success' })
    } else {
      toast({ title: 'Save failed', description: res.message, variant: 'destructive' })
    }
  }

  const handleSaveBusiness = async () => {
    if (!bizId) {
      toast({ title: 'Choose a business', variant: 'info' })
      return
    }
    setBusy(true)
    const res = await setControlPrompt(bizPrompt, bizId)
    setBusy(false)
    if (res.success) {
      setSaved({ where: businesses.find(b => b.id === bizId)?.name ?? bizId, version: res.data.version })
      load()
      toast({ title: 'Business override updated', description: `Now version ${res.data.version}`, variant: 'success' })
    } else {
      toast({ title: 'Save failed', description: res.message, variant: 'destructive' })
    }
  }

  const handleSaveLanding = async () => {
    setBusy(true)
    const res = await setLandingContent(landing)
    setBusy(false)
    if (res.success) {
      setLanding(res.data.landing_content)
      toast({ title: 'Landing content saved', description: 'Live on the public marketing page.', variant: 'success' })
    } else {
      toast({ title: 'Save failed', description: res.message, variant: 'destructive' })
    }
  }

  if (error && !prompt) return <ErrorState message={error} />
  if (!prompt) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-10 w-72" />
        <Skeleton className="h-64 w-full" />
        <Skeleton className="h-48 w-full" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Prompts & Landing</h1>
        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
          Versioned, audited control prompts for the agent supervisor, plus the public marketing
          landing content.
        </p>
      </div>

      {/* Master control prompt */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-lg">
            <FileText className="h-5 w-5 text-indigo-600 dark:text-indigo-400" /> Master control prompt
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-gray-600 dark:text-gray-300">
            Layered into every supervisor analysis as operating instructions. Global by default;
            a per-business override below takes precedence for that business.
          </p>
          <label htmlFor="master-prompt" className="sr-only">
            Master control prompt
          </label>
          <textarea
            id="master-prompt"
            value={promptText}
            onChange={e => setPromptText(e.target.value)}
            rows={6}
            className="mt-3 w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:border-gray-600 dark:bg-gray-800 dark:text-white"
            placeholder="Operating instructions for all businesses…"
          />
          <div className="mt-3 flex flex-wrap items-center gap-3">
            <Button onClick={handleSaveMaster} loading={busy}>
              <PenLine className="h-4 w-4" /> Save master prompt
            </Button>
            <span className="text-xs text-gray-500">
              Current version: {prompt.version} · last updated{' '}
              {prompt.updated_at ? new Date(prompt.updated_at).toLocaleString() : 'never'}
            </span>
          </div>
        </CardContent>
      </Card>

      {/* Per-business override */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-lg">
            <FileText className="h-5 w-5 text-indigo-600 dark:text-indigo-400" /> Per-business override
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-gray-600 dark:text-gray-300">
            When set, this instruction completely replaces the master prompt for the selected business.
          </p>
          <div className="mt-3 max-w-md">
            <label htmlFor="biz-select" className="text-sm font-medium text-gray-700 dark:text-gray-300">
              Business
            </label>
            <select
              id="biz-select"
              value={bizId}
              onChange={e => setBizId(e.target.value)}
              className="mt-1 flex h-10 w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:border-gray-600 dark:bg-gray-800 dark:text-white"
            >
              <option value="">Select a business…</option>
              {businesses.map(b => (
                <option key={b.id} value={b.id}>
                  {b.name}
                </option>
              ))}
            </select>
          </div>
          <label htmlFor="biz-prompt" className="sr-only">
            Business override prompt
          </label>
          <textarea
            id="biz-prompt"
            value={bizPrompt}
            onChange={e => setBizPrompt(e.target.value)}
            rows={4}
            className="mt-3 w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:border-gray-600 dark:bg-gray-800 dark:text-white"
            placeholder="Operating instructions for this business…"
          />
          <div className="mt-3 flex items-center gap-3">
            <Button variant="secondary" onClick={handleSaveBusiness} loading={busy}>
              Save override
            </Button>
            {saved && saved.where !== 'master' && (
              <span className="text-xs text-gray-500">
                {saved.where} now at version {saved.version}
              </span>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Prompt history */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-lg">
            <History className="h-5 w-5 text-indigo-600 dark:text-indigo-400" /> Prompt history (master)
          </CardTitle>
        </CardHeader>
        <CardContent>
          {history.length === 0 ? (
            <p className="text-sm text-gray-500">No previous versions — the master prompt is new.</p>
          ) : (
            <ul className="divide-y divide-gray-200 dark:divide-gray-700">
              {history.map(h => (
                <li key={h.version} className="py-3">
                  <p className="text-xs font-semibold uppercase tracking-wide text-gray-500">
                    Version {h.version}
                    {h.changed_at ? ` · ${new Date(h.changed_at).toLocaleString()}` : ''}
                  </p>
                  <p className="mt-1 whitespace-pre-wrap text-sm text-gray-700 dark:text-gray-200">
                    {h.instruction}
                  </p>
                </li>
              ))}
            </ul>
          )}
        </CardContent>
      </Card>

      {/* Landing content */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-lg">
            <PenLine className="h-5 w-5 text-indigo-600 dark:text-indigo-400" /> Public landing content
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-gray-600 dark:text-gray-300">
            Edits go live on the public marketing page immediately. Only these fields can be changed.
          </p>
          <div className="mt-3 grid gap-4 sm:grid-cols-2">
            {LANDING_FIELDS.map(field => (
              <div key={field.key}>
                <label htmlFor={field.key} className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  {field.label}
                </label>
                <Input
                  id={field.key}
                  value={landing[field.key] ?? ''}
                  onChange={e =>
                    setLanding(prev => ({ ...prev, [field.key]: e.target.value }))
                  }
                  placeholder={field.hint.split('.')[0]}
                  className="mt-1"
                />
                <p className="mt-0.5 text-xs text-gray-500">{field.hint}</p>
              </div>
            ))}
          </div>
          <div className="mt-4">
            <Button onClick={handleSaveLanding} loading={busy}>
              Save landing content
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}