/**
 * BoostMedia AI Content Generator Admin - Reporters Page
 *
 * @package BoostMedia_AI
 * @license GPL-2.0-or-later
 */

import { useCallback, useEffect, useMemo, useState } from 'react'
import { Copy, Plus, Sparkles, Star, Trash2, UserRound } from 'lucide-react'
import { Header } from '../components/layout/Header'
import { Badge, Button, Card } from '../components/common'
import { SetupBanner } from '../components/onboarding/SetupBanner'
import { TagInput } from '../components/generator/TagInput'
import { ReporterBuilder } from '../components/reporters/ReporterBuilder'
import { endpoints } from '../api/client'
import type { Reporter } from '../types'
import { t } from '../lib/i18n'

type ReporterFilter = 'all' | 'default' | 'recent' | 'archived'

type ReporterDraft = Omit<
  Reporter,
  'id' | 'uuid' | 'slug' | 'created_at' | 'updated_at' | 'last_used_at'
>

function createEmptyDraft(): ReporterDraft {
  return {
    name: '',
    language: window.bmaiSettings?.dataLanguage || 'he',
    writing_language: window.bmaiSettings?.dataLanguage || 'he',
    is_default: 0,
    status: 'active',
    specializations: [],
    writing_style: 'conversational',
    depth_level: 'detailed',
    tone: 'friendly',
    perspective: 'third_person',
    gender: 'neutral',
    language_quirks: [],
    audience: '',
    custom_instructions: '',
    source_mode: 'manual',
    builder_summary: '',
  }
}

function formatReporterSummary(reporter: Reporter | ReporterDraft): string {
  return [reporter.writing_style, reporter.tone, reporter.depth_level]
    .filter(Boolean)
    .map((item) => t(item))
    .join(' / ')
}

function formatDate(value: string | null): string {
  if (!value) {
    return t('Never used')
  }

  const date = new Date(value)
  if (Number.isNaN(date.getTime())) {
    return t('Never used')
  }

  return date.toLocaleString()
}

export default function ReportersPage() {
  const [reporters, setReporters] = useState<Reporter[]>([])
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [filter, setFilter] = useState<ReporterFilter>('all')
  const [selectedId, setSelectedId] = useState<number | null>(null)
  const [draft, setDraft] = useState<ReporterDraft>(createEmptyDraft())
  const [isCreating, setIsCreating] = useState(false)
  const [statusMessage, setStatusMessage] = useState<string | null>(null)
  const [builderOpen, setBuilderOpen] = useState(false)
  const [builderReporter, setBuilderReporter] = useState<Reporter | null>(null)

  const loadReporters = useCallback(async () => {
    setLoading(true)
    try {
      const res = await endpoints.getReporters('all')
      const items = (res.data as Reporter[]) || []
      setReporters(items)
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    void loadReporters()
  }, [loadReporters])

  useEffect(() => {
    if (reporters.length > 0 && !selectedId && !isCreating) {
      const defaultReporter = reporters.find((r) => r.is_default) || reporters[0]
      if (defaultReporter) setSelectedId(defaultReporter.id)
    }
  }, [reporters, isCreating])

  const selectedReporter = useMemo(
    () => reporters.find((reporter) => reporter.id === selectedId) || null,
    [reporters, selectedId],
  )

  useEffect(() => {
    if (selectedReporter && !isCreating) {
      setDraft({
        name: selectedReporter.name,
        language: selectedReporter.language,
        writing_language: selectedReporter.writing_language || selectedReporter.language,
        is_default: selectedReporter.is_default,
        status: selectedReporter.status,
        specializations: selectedReporter.specializations || [],
        writing_style: selectedReporter.writing_style,
        depth_level: selectedReporter.depth_level,
        tone: selectedReporter.tone,
        perspective: selectedReporter.perspective,
        gender: selectedReporter.gender || 'neutral',
        language_quirks: selectedReporter.language_quirks || [],
        audience: selectedReporter.audience || '',
        custom_instructions: selectedReporter.custom_instructions || '',
        source_mode: selectedReporter.source_mode,
        builder_summary: selectedReporter.builder_summary || '',
      })
    }
  }, [isCreating, selectedReporter])

  const filteredReporters = useMemo(() => {
    switch (filter) {
      case 'default':
        return reporters.filter((r) => r.is_default && r.status !== 'archived')
      case 'recent':
        return [...reporters]
          .filter((r) => r.last_used_at && r.status !== 'archived')
          .sort((a, b) => new Date(b.last_used_at || 0).getTime() - new Date(a.last_used_at || 0).getTime())
      case 'archived':
        return reporters.filter((r) => r.status === 'archived')
      default:
        return reporters
    }
  }, [filter, reporters])

  const activeReportersCount = useMemo(
    () => reporters.filter((reporter) => reporter.status === 'active').length,
    [reporters],
  )

  const hasOnlyDefaultReporter = activeReportersCount <= 1 && reporters.some((reporter) => reporter.is_default)

  const updateDraft = <K extends keyof ReporterDraft>(key: K, value: ReporterDraft[K]) => {
    setDraft((current) => ({ ...current, [key]: value }))
  }

  const handleCreate = () => {
    setIsCreating(true)
    setSelectedId(null)
    setDraft(createEmptyDraft())
    setStatusMessage(null)
  }

  const handleSelect = (reporter: Reporter) => {
    setIsCreating(false)
    setSelectedId(reporter.id)
    setStatusMessage(null)
  }

  const openCreateBuilder = () => {
    setBuilderReporter(null)
    setBuilderOpen(true)
  }

  const openRefineBuilder = () => {
    if (!selectedReporter) {
      return
    }
    setBuilderReporter(selectedReporter)
    setBuilderOpen(true)
  }

  const handleCancel = () => {
    setStatusMessage(null)
    setIsCreating(false)

    if (reporters.length > 0) {
      const fallback = reporters.find((r) => r.is_default) || reporters[0]
      if (fallback) setSelectedId(fallback.id)
    } else {
      setSelectedId(null)
      setDraft(createEmptyDraft())
    }
  }

  const handleSave = async () => {
    if (!draft.name.trim()) {
      setStatusMessage(t('Reporter name is required'))
      return
    }

    setSaving(true)
    setStatusMessage(null)
    try {
      if (isCreating) {
        const res = await endpoints.createReporter(draft)
        const created = res.data as Reporter
        setIsCreating(false)
        setSelectedId(created.id)
      } else if (selectedId) {
        await endpoints.updateReporter(selectedId, draft)
      }

      await loadReporters()
      setStatusMessage(t('Reporter saved'))
    } catch {
      setStatusMessage(t('Failed to save reporter'))
    } finally {
      setSaving(false)
    }
  }

  const handleDuplicate = async (reporterId: number) => {
    setSaving(true)
    setStatusMessage(null)
    try {
      const res = await endpoints.duplicateReporter(reporterId)
      const duplicated = res.data as Reporter
      await loadReporters()
      setSelectedId(duplicated.id)
      setIsCreating(false)
      setStatusMessage(t('Reporter duplicated'))
    } catch {
      setStatusMessage(t('Failed to duplicate reporter'))
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async (reporterId: number) => {
    if (!confirm(t('Archive this reporter?'))) {
      return
    }

    setSaving(true)
    setStatusMessage(null)
    try {
      await endpoints.deleteReporter(reporterId)
      const fallback = reporters.find((reporter) => reporter.id !== reporterId && reporter.status === 'active')
      setSelectedId(fallback?.id ?? null)
      setIsCreating(false)
      await loadReporters()
      setStatusMessage(t('Reporter archived'))
    } catch {
      setStatusMessage(t('Failed to archive reporter'))
    } finally {
      setSaving(false)
    }
  }

  const handleSetDefault = async (reporterId: number) => {
    setSaving(true)
    setStatusMessage(null)
    try {
      await endpoints.setDefaultReporter(reporterId)
      await loadReporters()
      setSelectedId(reporterId)
      setStatusMessage(t('Default reporter updated'))
    } catch {
      setStatusMessage(t('Failed to update default reporter'))
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="min-h-screen">
      <Header
        title={t('Reporters')}
        subtitle={t('Manage reusable AI reporter personas for content generation')}
        helpContent={[
          t('Reporters define the writing style, tone, expertise, and personality of your AI-generated content.'),
          t('A default reporter was created in your site\'s language. Customize it to match your brand voice.'),
          t('Create multiple reporters for different content types or audiences.'),
          t('Each reporter can have unique specializations and language quirks.'),
        ]}
      />

      <div className="p-6">
        <SetupBanner
          stepKey="reportersSeen"
          icon={'\u{270D}\uFE0F'}
          title={t('Meet your AI reporter')}
          description={t('A default reporter was created for your site\'s language. The reporter defines the writing style, tone, and expertise of your content. Take a moment to review their profile — you don\'t need to define what they write about now, just who they are. You can always create more reporters with different styles later.')}
          nextLabel={t('Start creating content')}
          nextPath="/generate"
        />
      </div>

      <div className="px-6 pb-6 grid grid-cols-1 xl:grid-cols-[minmax(0,420px)_minmax(0,1fr)] gap-6">
        <Card>
          <div className="flex flex-wrap items-start justify-between gap-3 mb-5">
            <div>
              <h2 className="text-lg font-semibold text-bc-gray-800">{t('Reporters')}</h2>
              <p className="text-sm text-bc-gray-500">{t('Create, edit, duplicate, archive, and choose the default reporter')}</p>
            </div>
            <div className="flex flex-wrap gap-2">
              <Button size="sm" onClick={openCreateBuilder} icon={<Sparkles className="w-4 h-4" />}>
                {t('Create with AI')}
              </Button>
              <Button size="sm" variant="secondary" onClick={handleCreate} icon={<Plus className="w-4 h-4" />}>
                {t('Create Reporter')}
              </Button>
            </div>
          </div>

          <div className="flex flex-wrap gap-2 mb-4">
            <Button size="sm" variant={filter === 'all' ? 'primary' : 'ghost'} onClick={() => setFilter('all')}>
              {t('All')}
            </Button>
            <Button size="sm" variant={filter === 'default' ? 'primary' : 'ghost'} onClick={() => setFilter('default')}>
              {t('Default')}
            </Button>
            <Button size="sm" variant={filter === 'recent' ? 'primary' : 'ghost'} onClick={() => setFilter('recent')}>
              {t('Recently Used')}
            </Button>
            <Button size="sm" variant={filter === 'archived' ? 'primary' : 'ghost'} onClick={() => setFilter('archived')}>
              {t('Archived')}
            </Button>
          </div>

          {loading ? (
            <div className="text-bc-gray-500">{t('Loading...')}</div>
          ) : filteredReporters.length === 0 ? (
            <div className="text-bc-gray-500">{t('No reporters found')}</div>
          ) : (
            <div className="space-y-3">
              {hasOnlyDefaultReporter ? (
                <div className="rounded-bc-md border border-dashed border-bc-primary/30 bg-bc-primary-light/40 px-4 py-3 text-sm text-bc-gray-700">
                  <strong className="block text-bc-gray-800 mb-1">{t('Create your first custom reporter')}</strong>
                  <span>{t('Start with AI for a guided setup, or create one manually if you already know the voice you want.')}</span>
                </div>
              ) : null}
              {filteredReporters.map((reporter) => (
                <button
                  key={reporter.id}
                  type="button"
                  onClick={() => handleSelect(reporter)}
                  className={`w-full rounded-bc-md border p-4 text-start transition-all ${
                    !isCreating && selectedId === reporter.id
                      ? 'border-bc-primary bg-bc-primary-light shadow-sm'
                      : 'border-bc-gray-200 bg-white hover:border-bc-gray-300 hover:shadow-sm'
                  }`}
                >
                  <div className="flex items-start justify-between gap-4">
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2 flex-wrap mb-1">
                        <span className="text-base font-semibold text-bc-gray-800">{reporter.name}</span>
                        {reporter.is_default ? (
                          <Badge variant="primary" dot>
                            {t('Default Reporter')}
                          </Badge>
                        ) : null}
                        {reporter.status === 'archived' ? (
                          <Badge variant="warning">{t('Archived')}</Badge>
                        ) : null}
                      </div>
                      <p className="text-sm text-bc-gray-500 leading-relaxed">{formatReporterSummary(reporter)}</p>
                      {reporter.builder_summary ? (
                        <p className="mt-2 text-sm text-bc-gray-600">{reporter.builder_summary}</p>
                      ) : null}
                    </div>
                    <UserRound className="w-4 h-4 text-bc-gray-400 shrink-0" />
                  </div>

                  <div className="flex flex-wrap gap-2 mt-4">
                    {(reporter.specializations || []).slice(0, 4).map((item, index) => (
                      <Badge key={`${item}-${index}`} variant="default">{item}</Badge>
                    ))}
                  </div>

                  <div className="mt-4 text-xs text-bc-gray-500">
                    {t('Last Used')}: {formatDate(reporter.last_used_at)}
                  </div>
                </button>
              ))}
            </div>
          )}
        </Card>

        <Card>
          <div className="flex flex-wrap items-start justify-between gap-3 mb-4">
            <div>
              <h2 className="text-lg font-semibold text-bc-gray-800">
                {isCreating ? t('Create Reporter') : selectedReporter ? t('Edit Reporter') : t('Reporter Details')}
              </h2>
              <p className="text-sm text-bc-gray-500">
                {isCreating ? t('Define a new reporter profile manually') : t('Edit the selected reporter profile')}
              </p>
            </div>
            {!isCreating && selectedReporter ? (
              <div className="flex flex-wrap gap-2">
                <Button size="sm" variant="secondary" onClick={openRefineBuilder} icon={<Sparkles className="w-4 h-4" />}>
                  {t('Refine with AI')}
                </Button>
                <Button size="sm" variant="ghost" onClick={() => handleDuplicate(selectedReporter.id)} icon={<Copy className="w-4 h-4" />}>
                  {t('Duplicate')}
                </Button>
                <Button size="sm" variant="ghost" onClick={() => handleDelete(selectedReporter.id)} icon={<Trash2 className="w-4 h-4" />}>
                  {t('Delete')}
                </Button>
                {!selectedReporter.is_default ? (
                  <Button size="sm" variant="secondary" onClick={() => handleSetDefault(selectedReporter.id)} icon={<Star className="w-4 h-4" />}>
                    {t('Make Default')}
                  </Button>
                ) : null}
              </div>
            ) : null}
          </div>

          {statusMessage ? (
            <div className="mb-4 rounded-bc border border-bc-gray-200 bg-bc-gray-50 px-3 py-2 text-sm text-bc-gray-700">
              {statusMessage}
            </div>
          ) : null}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <label className="block">
              <span className="block font-semibold text-bc-gray-700 mb-2">{t('Name')}</span>
              <input
                type="text"
                value={draft.name}
                onChange={(e) => updateDraft('name', e.target.value)}
                className="w-full px-3 py-2 border border-bc-gray-300 rounded-bc"
              />
            </label>

            <label className="block">
              <span className="block font-semibold text-bc-gray-700 mb-2">{t('Audience')}</span>
              <input
                type="text"
                value={draft.audience}
                onChange={(e) => updateDraft('audience', e.target.value)}
                className="w-full px-3 py-2 border border-bc-gray-300 rounded-bc"
              />
            </label>

            <label className="block">
              <span className="block font-semibold text-bc-gray-700 mb-2">{t('Writing Style')}</span>
              <input
                type="text"
                value={draft.writing_style}
                onChange={(e) => updateDraft('writing_style', e.target.value)}
                placeholder={t('e.g., conversational, formal, academic, or describe your own...')}
                className="w-full px-3 py-2 border border-bc-gray-300 rounded-bc"
              />
            </label>

            <label className="block">
              <span className="block font-semibold text-bc-gray-700 mb-2">{t('Depth Level')}</span>
              <input
                type="text"
                value={draft.depth_level}
                onChange={(e) => updateDraft('depth_level', e.target.value)}
                placeholder={t('e.g., concise overview, detailed walkthrough, expert-level detail...')}
                className="w-full px-3 py-2 border border-bc-gray-300 rounded-bc"
              />
            </label>

            <label className="block">
              <span className="block font-semibold text-bc-gray-700 mb-2">{t('Tone')}</span>
              <input
                type="text"
                value={draft.tone}
                onChange={(e) => updateDraft('tone', e.target.value)}
                placeholder={t('e.g., authoritative but warm, analytical, playful...')}
                className="w-full px-3 py-2 border border-bc-gray-300 rounded-bc"
              />
            </label>

            <label className="block">
              <span className="block font-semibold text-bc-gray-700 mb-2">{t('Perspective')}</span>
              <input
                type="text"
                value={draft.perspective}
                onChange={(e) => updateDraft('perspective', e.target.value)}
                placeholder={t('e.g., mostly third person, first person for tips, editorial we...')}
                className="w-full px-3 py-2 border border-bc-gray-300 rounded-bc"
              />
            </label>

            <label className="block">
              <span className="block font-semibold text-bc-gray-700 mb-2">{t('Reporter gender')}</span>
              <select
                value={draft.gender}
                onChange={(e) => updateDraft('gender', e.target.value as ReporterDraft['gender'])}
                className="w-full px-3 py-2 border border-bc-gray-300 rounded-bc"
              >
                <option value="male">{t('Male')}</option>
                <option value="female">{t('Female')}</option>
                <option value="neutral">{t('Neutral')}</option>
              </select>
              <span className="mt-2 block text-xs text-bc-gray-500">{t('Affects Hebrew grammar in conversations')}</span>
            </label>

            <label className="block">
              <span className="block font-semibold text-bc-gray-700 mb-2">{t('Writing Language')}</span>
              <select
                value={draft.writing_language}
                onChange={(e) => updateDraft('writing_language', e.target.value)}
                className="w-full px-3 py-2 border border-bc-gray-300 rounded-bc"
              >
                <option value="he">{t('Hebrew')}</option>
                <option value="en">{t('English')}</option>
              </select>
              <span className="mt-2 block text-xs text-bc-gray-500">{t('The language this reporter communicates and writes in')}</span>
            </label>
          </div>

          <div className="mt-4">
            <span className="block font-semibold text-bc-gray-700 mb-2">{t('Specializations')}</span>
            <TagInput
              tags={draft.specializations}
              onChange={(value) => updateDraft('specializations', value)}
              placeholder={t('Add specialization...')}
              maxTags={12}
            />
          </div>

          <div className="mt-4">
            <span className="block font-semibold text-bc-gray-700 mb-2">{t('Language Quirks')}</span>
            <TagInput
              tags={draft.language_quirks}
              onChange={(value) => updateDraft('language_quirks', value)}
              placeholder={t('Add language quirk...')}
              maxTags={12}
            />
          </div>

          <div className="mt-4">
            <span className="block font-semibold text-bc-gray-700 mb-2">{t('Custom Instructions')}</span>
            <textarea
              value={draft.custom_instructions}
              onChange={(e) => updateDraft('custom_instructions', e.target.value)}
              rows={5}
              className="w-full px-3 py-2 border border-bc-gray-300 rounded-bc"
            />
          </div>

          <div className="mt-6 flex items-center justify-between gap-3">
            <div className="text-sm text-bc-gray-500">
              {t('Default')}: {draft.is_default ? t('Yes') : t('No')}
            </div>
            <div className="flex gap-2">
              <Button variant="ghost" onClick={handleCancel}>
                {t('Cancel')}
              </Button>
              <Button onClick={handleSave} loading={saving}>
                {isCreating ? t('Save Reporter') : t('Save Changes')}
              </Button>
            </div>
          </div>
        </Card>
      </div>

      <ReporterBuilder
        open={builderOpen}
        initialReporter={builderReporter}
        onClose={() => setBuilderOpen(false)}
        onSaved={(reporter) => {
          setBuilderOpen(false)
          setBuilderReporter(null)
          setSelectedId(reporter.id)
          setIsCreating(false)
          setStatusMessage(null)
          void loadReporters()
        }}
        onUseManualDraft={(builderDraft) => {
          setBuilderOpen(false)
          setStatusMessage(null)
          setIsCreating(!builderReporter)
          setDraft((current) => ({
            ...current,
            ...builderDraft,
          }))
        }}
      />
    </div>
  )
}
