import { useEffect, useMemo, useState } from 'react';
import {
  Alert, Badge, Button, Card, Col, DatePicker, Descriptions, Divider, Drawer, Empty, Form,
  Input, InputNumber, List, Modal, Progress, Radio, Row, Segmented, Select, Space, Spin,
  Statistic, Steps, Switch, Table, Tabs, Tag, Timeline, Tooltip, Typography, message,
} from 'antd';
import {
  ApiOutlined, AuditOutlined, BookOutlined, BulbOutlined, CalendarOutlined, CheckCircleOutlined,
  ClockCircleOutlined, DollarOutlined, DownloadOutlined, ExperimentOutlined, EyeOutlined,
  FileTextOutlined, FundProjectionScreenOutlined, GlobalOutlined, LineChartOutlined, MailOutlined, PlayCircleOutlined,
  PlusOutlined, ReloadOutlined, RobotOutlined, SafetyCertificateOutlined, SendOutlined,
  SettingOutlined, ShareAltOutlined, TeamOutlined, ToolOutlined,
} from '@ant-design/icons';
import { useLocation, useNavigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
import dayjs from 'dayjs';
import { request } from '@/request';
import { selectCurrentAdmin } from '@/redux/auth/selectors';
import { canAccessPermission } from '@/utils/permissions';
import { WorkflowPage } from './shared';
import useMoney from '@/settings/useMoney';
import './agentStudio.css';

const { Paragraph, Text, Title } = Typography;
const STUDIO_NAV = [
  ['library', 'Agent Library', RobotOutlined], ['builder', 'Builder', SettingOutlined],
  ['runs', 'Runs & Approvals', AuditOutlined], ['calendar', 'Agent Calendar', CalendarOutlined], ['knowledge', 'Knowledge', BookOutlined],
  ['tools', 'Tools', ToolOutlined], ['brand', 'Brand Center', BulbOutlined],
  ['social', 'Social Scheduler', CalendarOutlined], ['budgets', 'Budgets', DollarOutlined],
  ['providers', 'Provider Accounts', ApiOutlined],
  ['docgen', 'Doc Generator', FileTextOutlined],
];
const BUILDER_STEPS = ['Purpose', 'Knowledge', 'Tools', 'Guardrails', 'Schedule', 'Test', 'Publish'];
const CHANNELS = ['facebook', 'instagram', 'linkedin', 'x', 'whatsapp'];
const CHANNEL_LABELS = { facebook: 'Facebook', instagram: 'Instagram', linkedin: 'LinkedIn', x: 'X', whatsapp: 'WhatsApp' };
const CHANNEL_COLORS = { facebook: '#1677ff', instagram: '#e1306c', linkedin: '#0a66c2', x: '#111827', whatsapp: '#25d366' };
const riskColor = { low: 'green', medium: 'gold', high: 'orange', critical: 'red' };
const statusColor = { published: 'green', succeeded: 'green', running: 'blue', queued: 'cyan', needs_approval: 'orange', failed: 'red', cancelled: 'default', draft: 'default', ready: 'green' };

const viewFromPath = (pathname) => pathname.split('/').filter(Boolean)[1] || 'library';
const listResult = (response) => response?.result || [];

function MarkdownOutput({ children }) {
  if (!children) return <Text type="secondary">No output yet.</Text>;
  return <div className="agent-markdown">{String(children).split('\n').map((line, index) => {
    if (line.startsWith('### ')) return <h4 key={index}>{line.slice(4)}</h4>;
    if (line.startsWith('## ')) return <h3 key={index}>{line.slice(3)}</h3>;
    if (/^\d+\. /.test(line)) return <div key={index} className="agent-list-line">{line}</div>;
    return line ? <p key={index}>{line.replace(/\*\*/g, '')}</p> : <br key={index} />;
  })}</div>;
}

function StudioRail({ view, onChange, pendingApprovals }) {
  return <aside className="agent-studio-rail">
    <div className="agent-studio-rail-title">AI Studio</div>
    {STUDIO_NAV.map(([key, label, Icon]) => (
      <button key={key} className={view === key ? 'active' : ''} onClick={() => onChange(key)}>
        <Icon /><span>{label}</span>{key === 'runs' && pendingApprovals ? <Badge count={pendingApprovals} size="small" /> : null}
      </button>
    ))}
  </aside>;
}

export default function AgentStudio() {
  const location = useLocation();
  const navigate = useNavigate();
  const currentAdmin = useSelector(selectCurrentAdmin);
  const money = useMoney();
  const view = viewFromPath(location.pathname);
  const [loading, setLoading] = useState(true);
  const [templates, setTemplates] = useState([]);
  const [tools, setTools] = useState([]);
  const [agents, setAgents] = useState([]);
  const [runs, setRuns] = useState([]);
  const [approvals, setApprovals] = useState([]);
  const [knowledge, setKnowledge] = useState([]);
  const [brands, setBrands] = useState([]);
  const [posts, setPosts] = useState([]);
  const [budgets, setBudgets] = useState([]);
  const [providerCatalog, setProviderCatalog] = useState([]);
  const [agentCalendar, setAgentCalendar] = useState([]);
  const [schedulePreview, setSchedulePreview] = useState(null);
  const [docTemplates, setDocTemplates] = useState([]);
  const [docTemplateId, setDocTemplateId] = useState(null);
  const [docPrompt, setDocPrompt] = useState('');
  const [docRecipient, setDocRecipient] = useState('');
  const [docSendEmail, setDocSendEmail] = useState(false);
  const [docResult, setDocResult] = useState(null);
  const [docBusy, setDocBusy] = useState(false);
  const [selectedAgentId, setSelectedAgentId] = useState();
  const [selectedRun, setSelectedRun] = useState();
  const [builderStep, setBuilderStep] = useState(0);
  const [assistantMessages, setAssistantMessages] = useState([{ role: 'assistant', content: 'Tell me the outcome you want. I can draft the purpose, tools, knowledge, and safe guardrails.' }]);
  const [assistantInput, setAssistantInput] = useState('');
  const [busy, setBusy] = useState(false);
  const [form] = Form.useForm();
  const selectedAgent = agents.find((item) => item._id === selectedAgentId) || agents[0];
  const canBuild = canAccessPermission(currentAdmin, 'ai.agent.create') || canAccessPermission(currentAdmin, 'ai.studio.create');

  const load = async () => {
    setLoading(true);
    const calls = await Promise.allSettled([
      request.get({ entity: 'agent/templates' }), request.get({ entity: 'agent/tools' }),
      request.list({ entity: 'agentdefinition', options: { page: 1, items: 100 } }),
      request.get({ entity: 'agent/run/history?limit=50' }), request.get({ entity: 'agent/approval' }),
      request.list({ entity: 'knowledgesource', options: { page: 1, items: 100 } }),
      request.list({ entity: 'brandprofile', options: { page: 1, items: 100 } }),
      request.list({ entity: 'socialpost', options: { page: 1, items: 100 } }),
      request.list({ entity: 'agentbudget', options: { page: 1, items: 100 } }),
      request.get({ entity: 'integrationaccount/providers' }),
      request.get({ entity: 'agent/calendar' }),
      request.get({ entity: 'ai/document/templates' }),
    ]);
    const value = (index) => calls[index].status === 'fulfilled' ? listResult(calls[index].value) : [];
    setTemplates(value(0)); setTools(value(1)); setAgents(value(2)); setRuns(value(3));
    setApprovals(value(4)); setKnowledge(value(5)); setBrands(value(6)); setPosts(value(7)); setBudgets(value(8));
    setProviderCatalog(value(9)); setAgentCalendar(value(10)); setDocTemplates(value(11));
    if (!selectedAgentId && value(2)[0]) setSelectedAgentId(value(2)[0]._id);
    setLoading(false);
  };

  useEffect(() => { load(); }, []);
  useEffect(() => {
    if (selectedAgent) form.setFieldsValue({
      name: selectedAgent.name, description: selectedAgent.description, specialistType: selectedAgent.specialistType,
      instructions: selectedAgent.instructions, provider: selectedAgent.modelPolicy?.provider || 'openai',
      fallbackProviders: selectedAgent.modelPolicy?.fallbackProviders || ['kimi'], temperature: selectedAgent.modelPolicy?.temperature ?? 0.3,
      maxOutputTokens: selectedAgent.modelPolicy?.maxOutputTokens || 2048, maxSteps: selectedAgent.modelPolicy?.maxSteps || 8,
      knowledgeSources: (selectedAgent.knowledgeSources || []).map((item) => item?._id || item), tools: selectedAgent.tools || [],
      approvalMode: selectedAgent.approvalPolicy?.mode || 'risk_based', approvalFor: selectedAgent.approvalPolicy?.approvalFor || [],
      scheduleEnabled: selectedAgent.schedule?.enabled, scheduleExpression: selectedAgent.schedule?.expression,
      tokenBudget: selectedAgent.limits?.tokenBudget || 50000, scrapedPagesPerRun: selectedAgent.limits?.scrapedPagesPerRun || 20,
    });
  }, [selectedAgentId, selectedAgent?._id]);

  const openView = (key) => navigate(key === 'library' ? '/ai-studio' : `/ai-studio/${key}`);
  const createAgent = async (templateKey = 'content_production') => {
    setBusy(true);
    const template = templates.find((item) => item.key === templateKey);
    const response = await request.post({ entity: 'agent/from-template', jsonData: { templateKey, name: template?.name } });
    await load(); setSelectedAgentId(response?.result?._id); openView('builder'); setBusy(false);
    message.success('Agent draft created');
  };
  const saveAgent = async () => {
    const values = await form.validateFields(); setBusy(true);
    const payload = {
      name: values.name, description: values.description, specialistType: values.specialistType, instructions: values.instructions,
      modelPolicy: { provider: values.provider, fallbackProviders: values.fallbackProviders, temperature: values.temperature, maxOutputTokens: values.maxOutputTokens, maxSteps: values.maxSteps },
      knowledgeSources: values.knowledgeSources || [], tools: values.tools || [],
      approvalPolicy: { mode: values.approvalMode, approvalFor: values.approvalFor || [] },
      schedule: { enabled: values.scheduleEnabled, expression: values.scheduleExpression, timezone: 'Africa/Lagos' },
      limits: { tokenBudget: values.tokenBudget, scrapedPagesPerRun: values.scrapedPagesPerRun, costBudget: { amount: 0, currency: 'NGN' } },
    };
    let response;
    if (selectedAgent?._id) response = await request.update({ entity: 'agentdefinition', id: selectedAgent._id, jsonData: payload });
    else response = await request.post({ entity: 'agent/from-template', jsonData: payload });
    await load(); setSelectedAgentId(response?.result?._id || selectedAgent?._id); setBusy(false); message.success('Agent saved');
  };
  const testAgent = async () => {
    if (!selectedAgent?._id) return message.warning('Save the agent before testing.');
    setBusy(true); const response = await request.post({ entity: `agent/${selectedAgent._id}/test`, jsonData: { objective: form.getFieldValue('description') || 'Validate this agent configuration', sample: true } });
    setSelectedRun(response?.result); setBuilderStep(4); await load(); setBusy(false); message.success('Safe test run completed');
  };
  const publishAgent = async () => {
    if (!selectedAgent?._id) return; setBusy(true); await request.post({ entity: `agent/${selectedAgent._id}/publish`, jsonData: {} }); await load(); setBusy(false); message.success('Agent published');
  };
  const previewAgentSchedule = async () => {
    if (!selectedAgent?._id) return;
    const response = await request.post({
      entity: `agent/${selectedAgent._id}/schedule/preview`,
      jsonData: { expression: form.getFieldValue('scheduleExpression'), timezone: 'Africa/Lagos' },
    });
    setSchedulePreview(response?.result || null);
  };
  const retryRun = async (run) => {
    await request.post({ entity: `agent/run/${run._id}/retry`, jsonData: {} });
    await load();
    message.success('Run retry queued');
  };
  const sendAssistant = async () => {
    const text = assistantInput.trim(); if (!text) return;
    setAssistantMessages((items) => [...items, { role: 'user', content: text }]); setAssistantInput(''); setBusy(true);
    const response = await request.post({ entity: 'agent/assistant/chat', jsonData: { message: text, context: form.getFieldsValue(true) } });
    setAssistantMessages((items) => [...items, { role: 'assistant', content: response?.result?.message || 'I prepared a safe recommendation for this agent.' }]); setBusy(false);
  };
  const decide = async (approval, decision) => { await request.post({ entity: `agent/approval/${approval._id}/decide`, jsonData: { decision } }); await load(); message.success(`Action ${decision}`); };

  const pendingApprovals = approvals.filter((item) => item.status === 'pending').length;

  const generateDocument = async () => {
    if (!docPrompt.trim()) return message.warning('Enter a description of the document to generate.');
    setDocBusy(true); setDocResult(null);
    try {
      const response = await request.post({
        entity: 'ai/document/generate-from-template',
        jsonData: { templateId: docTemplateId, prompt: docPrompt, recipientEmail: docRecipient, sendEmail: docSendEmail },
      });
      setDocResult(response?.result || null);
      if (response?.result) message.success(response.message || 'Document generated successfully');
    } catch { message.error('Generation failed. Please try again.'); }
    setDocBusy(false);
  };

  const content = loading ? <div className="agent-loading"><Spin size="large" /></div> : (
    view === 'library' ? <LibraryView {...{ templates, agents, runs, createAgent, busy, openBuilder: (id) => { setSelectedAgentId(id); openView('builder'); } }} /> :
    view === 'builder' ? <BuilderView {...{ form, templates, tools, knowledge, brands, selectedAgent, agents, setSelectedAgentId, builderStep, setBuilderStep, saveAgent, testAgent, publishAgent, busy, selectedRun, assistantMessages, assistantInput, setAssistantInput, sendAssistant, schedulePreview, previewAgentSchedule }} /> :
    view === 'runs' ? <RunsView {...{ runs, approvals, selectedRun, setSelectedRun, decide, money, retryRun }} /> :
    view === 'calendar' ? <AgentCalendarView items={agentCalendar} runs={runs} /> :
    view === 'knowledge' ? <KnowledgeView items={knowledge} reload={load} /> :
    view === 'tools' ? <ToolsView tools={tools} /> :
    view === 'brand' ? <BrandView items={brands} reload={load} /> :
    view === 'social' ? <SocialView items={posts} reload={load} /> :
    view === 'providers' ? <ProvidersView items={providerCatalog} reload={load} currentAdmin={currentAdmin} /> :
    view === 'docgen' ? <DocGeneratorView {...{ docTemplates, docTemplateId, setDocTemplateId, docPrompt, setDocPrompt, docRecipient, setDocRecipient, docSendEmail, setDocSendEmail, docResult, docBusy, generateDocument, reload: load }} /> :
    <BudgetsView items={budgets} money={money} reload={load} />
  );

  return <WorkflowPage title="AI Studio" description="Build, govern, run, and monitor custom AI agents across your business." permission="ai.studio.read" extra={<Space><Tag color="green">Provider neutral</Tag><Button icon={<ReloadOutlined />} onClick={load}>Refresh</Button></Space>}>
    <div className="agent-studio-shell"><StudioRail view={view} onChange={openView} pendingApprovals={pendingApprovals} /><main className="agent-studio-main">{content}</main></div>
  </WorkflowPage>;
}

function LibraryView({ templates, agents, runs, createAgent, busy, openBuilder }) {
  return <Space direction="vertical" size={20} style={{ width: '100%' }}>
    <div className="agent-view-heading"><div><Title level={3}>Agent Library</Title><Paragraph type="secondary">Start from a specialist or create a governed agent for a specific business outcome.</Paragraph></div><Button type="primary" icon={<PlusOutlined />} loading={busy} onClick={() => createAgent('content_production')}>Create agent</Button></div>
    <Row gutter={[12, 12]}>{templates.map((template) => <Col xs={24} md={12} xl={8} key={template.key}><Card className="agent-template" hoverable onClick={() => createAgent(template.key)}><RobotOutlined className="agent-template-icon" /><Title level={5}>{template.name}</Title><Paragraph ellipsis={{ rows: 2 }}>{template.description}</Paragraph><Space wrap>{template.tools.slice(0, 3).map((tool) => <Tag key={tool}>{tool.split('.').pop()}</Tag>)}</Space></Card></Col>)}</Row>
    <Card title="Your agents" extra={<Text type="secondary">{agents.length} agents</Text>}><Table rowKey="_id" dataSource={agents} pagination={false} columns={[
      { title: 'Agent', render: (_, item) => <Space><RobotOutlined /><div><Text strong>{item.name}</Text><br/><Text type="secondary">{item.description || item.specialistType}</Text></div></Space> },
      { title: 'Status', dataIndex: 'status', render: (value) => <Tag color={statusColor[value]}>{value}</Tag> },
      { title: 'Version', dataIndex: 'version', render: (value) => `v${value || 0}` },
      { title: 'Recent runs', render: (_, item) => runs.filter((run) => (run.agent?._id || run.agent) === item._id).length },
      { title: '', render: (_, item) => <Button onClick={() => openBuilder(item._id)}>Open builder</Button> },
    ]}/></Card>
  </Space>;
}

function BuilderView(props) {
  const { form, templates, tools, knowledge, selectedAgent, agents, setSelectedAgentId, builderStep, setBuilderStep, saveAgent, testAgent, publishAgent, busy, selectedRun, assistantMessages, assistantInput, setAssistantInput, sendAssistant, schedulePreview, previewAgentSchedule } = props;
  const selectedTools = Form.useWatch('tools', form) || [];
  return <div className="agent-builder-grid">
    <section className="agent-builder-canvas">
      <div className="agent-view-heading"><div><Space><Select value={selectedAgent?._id} placeholder="New agent" style={{ minWidth: 220 }} onChange={setSelectedAgentId} options={agents.map((item) => ({ value: item._id, label: item.name }))}/><Tag color={statusColor[selectedAgent?.status]}>{selectedAgent?.status || 'new'}</Tag><Tag color={(selectedAgent?.modelPolicy?.provider || form.getFieldValue('provider')) === 'hermes' ? 'green' : 'blue'}>{(selectedAgent?.modelPolicy?.provider || form.getFieldValue('provider') || 'hermes').toUpperCase()} orchestration</Tag></Space><Title level={3}>Build an AI Agent</Title></div><Space><Button onClick={saveAgent} loading={busy}>Save</Button><Button onClick={previewAgentSchedule} disabled={!selectedAgent}>Preview schedule</Button><Button type="primary" onClick={publishAgent} disabled={!selectedAgent}>Publish</Button></Space></div>
      <Steps current={builderStep} onChange={setBuilderStep} responsive items={BUILDER_STEPS.map((title) => ({ title }))}/>
      <Form form={form} layout="vertical" className="agent-builder-form" initialValues={{ provider: 'hermes', fallbackProviders: ['openai', 'kimi'], temperature: 0.3, maxOutputTokens: 2048, maxSteps: 8, approvalMode: 'risk_based', tokenBudget: 50000, scrapedPagesPerRun: 20 }}>
        <Row gutter={14}>
          <Col xs={24} lg={14}><Card title="Agent identity" size="small"><Form.Item name="name" label="Agent name" rules={[{ required: true }]}><Input placeholder="Growth Strategist" /></Form.Item><Form.Item name="specialistType" label="Specialist template"><Select options={templates.map((item) => ({ value: item.key, label: item.name }))}/></Form.Item><Form.Item name="description" label="Primary outcome"><Input placeholder="Analyze markets and propose actionable growth strategies" /></Form.Item><Form.Item name="instructions" label="Role and instructions" rules={[{ required: true }]}><Input.TextArea rows={6} /></Form.Item></Card></Col>
          <Col xs={24} lg={10}><Card title="Model" size="small"><Form.Item name="provider" label="Primary provider"><Select options={[{ value: 'hermes', label: 'Hermes' }, { value: 'openai', label: 'OpenAI' }, { value: 'kimi', label: 'Kimi' }]}/></Form.Item><Form.Item name="fallbackProviders" label="Fallback providers"><Select mode="multiple" options={[{ value: 'openai', label: 'OpenAI' }, { value: 'kimi', label: 'Kimi' }, { value: 'hermes', label: 'Hermes' }]}/></Form.Item><Alert type="info" showIcon message="Hermes plans the run. Content-heavy or fallback steps can still use OpenAI or Kimi." style={{ marginBottom: 12 }} /><Form.Item name="temperature" label="Creativity"><InputNumber min={0} max={2} step={0.1} style={{ width: '100%' }}/></Form.Item><Row gutter={8}><Col span={12}><Form.Item name="maxOutputTokens" label="Output tokens"><InputNumber min={256} style={{ width: '100%' }}/></Form.Item></Col><Col span={12}><Form.Item name="maxSteps" label="Max steps"><InputNumber min={1} max={30} style={{ width: '100%' }}/></Form.Item></Col></Row></Card></Col>
        </Row>
        <Row gutter={14}>
          <Col xs={24} lg={8}><Card title="Knowledge sources" size="small"><Form.Item name="knowledgeSources"><Select mode="multiple" placeholder="Attach sources" options={knowledge.map((item) => ({ value: item._id, label: item.name }))}/></Form.Item><List size="small" dataSource={knowledge.slice(0, 3)} renderItem={(item) => <List.Item><Space><BookOutlined/><span>{item.name}</span></Space><Tag color={statusColor[item.status]}>{item.status}</Tag></List.Item>}/></Card></Col>
          <Col xs={24} lg={8}><Card title="Allowed tools" size="small"><Form.Item name="tools"><Select mode="multiple" placeholder="Add tools" options={tools.map((item) => ({ value: item.key, label: item.label }))}/></Form.Item><Space wrap>{selectedTools.map((key) => { const item = tools.find((tool) => tool.key === key); return <Tag color={riskColor[item?.riskLevel]} key={key}>{item?.label || key}</Tag>; })}</Space></Card></Col>
          <Col xs={24} lg={8}><Card title="Execution & guardrails" size="small"><Form.Item name="approvalMode" label="Approval policy"><Select options={[{ value: 'risk_based', label: 'Approval by risk' }, { value: 'always', label: 'Always approve writes' }, { value: 'autonomous', label: 'Autonomous within limits' }]}/></Form.Item><Form.Item name="approvalFor" label="Additional approval tools"><Select mode="multiple" options={tools.filter((item) => item.riskLevel !== 'low').map((item) => ({ value: item.key, label: item.label }))}/></Form.Item><Form.Item name="scheduleEnabled" label="Scheduled runs" valuePropName="checked"><Switch /></Form.Item><Form.Item name="scheduleExpression" label="Schedule"><Input placeholder="daily@09:00, weekly:mon@09:00, monthly:15@09:00, or cron" /></Form.Item>{schedulePreview?.nextRunAt ? <Alert type="success" showIcon message={`Next run: ${dayjs(schedulePreview.nextRunAt).format('DD MMM YYYY, HH:mm')}`} style={{ marginBottom: 12 }} /> : null}<Row gutter={8}><Col span={12}><Form.Item name="tokenBudget" label="Token limit"><InputNumber min={1000} style={{ width: '100%' }}/></Form.Item></Col><Col span={12}><Form.Item name="scrapedPagesPerRun" label="Page limit"><InputNumber min={0} max={100} style={{ width: '100%' }}/></Form.Item></Col></Row></Card></Col>
        </Row>
      </Form>
      <Card className="agent-test-console" title={<Space><ExperimentOutlined/>Test run</Space>} extra={<Button type="primary" icon={<PlayCircleOutlined />} loading={busy} onClick={testAgent}>Run safe test</Button>}>
        {selectedRun ? <RunTimeline run={selectedRun} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="Test mode simulates external writes and shows approval gates before publishing." />}
      </Card>
    </section>
    <aside className="agent-assistant"><div className="agent-assistant-header"><RobotOutlined/><div><Text strong>AI Assistant</Text><br/><Text type="secondary">Agent setup copilot</Text></div></div><div className="agent-assistant-messages">{assistantMessages.map((item, index) => <div key={index} className={`agent-chat ${item.role}`}><MarkdownOutput>{item.content}</MarkdownOutput></div>)}</div><div className="agent-assistant-input"><Input.TextArea autoSize={{ minRows: 2, maxRows: 5 }} value={assistantInput} onChange={(event) => setAssistantInput(event.target.value)} placeholder="Ask for an agent, tools, or guardrails..."/><Button type="primary" icon={<SendOutlined />} loading={busy} onClick={sendAssistant}>Send</Button></div></aside>
  </div>;
}

function RunTimeline({ run }) { return <><Space wrap><Tag color={statusColor[run.status]}>{run.status}</Tag><Text>Step {run.currentStep || 0}</Text><Text>{run.usage?.totalTokens || 0} tokens</Text><Text>{run.cost?.currency || 'NGN'} {run.cost?.amount || 0}</Text></Space><Divider/>{Array.isArray(run.steps) && run.steps.length ? <Timeline items={run.steps.map((step) => ({ color: step.status === 'failed' ? 'red' : step.status === 'needs_approval' ? 'orange' : 'green', children: <Space direction="vertical" size={0}><Text strong>{step.tool || step.kind}</Text><Text type="secondary">{step.outputSummary || step.error || step.status}</Text></Space> }))} /> : null}<MarkdownOutput>{run.output?.content || 'The test run validated configured tools. Sensitive actions remain simulated.'}</MarkdownOutput></>; }

function RunsView({ runs, approvals, selectedRun, setSelectedRun, decide, money, retryRun }) {
  return <Space direction="vertical" size={16} style={{ width: '100%' }}><div className="agent-view-heading"><div><Title level={3}>Runs & Approvals</Title><Paragraph type="secondary">Inspect execution steps, costs, errors, and sensitive actions waiting for a person.</Paragraph></div></div><Row gutter={12}><Col span={6}><Card><Statistic title="Running" value={runs.filter((r) => r.status === 'running').length}/></Card></Col><Col span={6}><Card><Statistic title="Needs approval" value={approvals.filter((a) => a.status === 'pending').length}/></Card></Col><Col span={6}><Card><Statistic title="Succeeded" value={runs.filter((r) => r.status === 'succeeded').length}/></Card></Col><Col span={6}><Card><Statistic title="Failed" value={runs.filter((r) => r.status === 'failed').length}/></Card></Col></Row>
  {approvals.filter((item) => item.status === 'pending').map((item) => <Alert key={item._id} type="warning" showIcon message={`${item.tool} requires approval`} description={<Space direction="vertical"><Text>{item.riskLevel} risk action requested by an agent.</Text><Space><Button type="primary" onClick={() => decide(item, 'approved')}>Approve</Button><Button danger onClick={() => decide(item, 'rejected')}>Reject</Button></Space></Space>}/>) }
  <Card title="Run history"><Table rowKey="_id" dataSource={runs} pagination={{ pageSize: 10 }} onRow={(record) => ({ onClick: async () => { const detail = await request.get({ entity: `agent/run/${record._id}` }); setSelectedRun(detail?.result || record); } })} columns={[{ title: 'Agent', dataIndex: 'agent', render: (value) => value?.name || value || '-' }, { title: 'Status', dataIndex: 'status', render: (value) => <Tag color={statusColor[value]}>{value}</Tag> }, { title: 'Trigger', dataIndex: 'trigger' }, { title: 'Tokens', render: (_, item) => item.usage?.totalTokens || 0 }, { title: 'Cost', render: (_, item) => money.moneyFormatter({ amount: item.cost?.amount || 0, currency_code: item.cost?.currency || 'NGN' }) }, { title: 'Started', dataIndex: 'startedAt', render: (value) => value ? dayjs(value).format('DD MMM, HH:mm') : '-' }, { title: 'Retry', render: (_, item) => item.status === 'failed' ? <Button size="small" onClick={(event) => { event.stopPropagation(); retryRun(item); }}>Retry</Button> : null }]}/></Card>
  <Drawer title="Run detail" open={Boolean(selectedRun)} onClose={() => setSelectedRun(null)} width={620}>{selectedRun && <RunTimeline run={selectedRun}/>}</Drawer></Space>;
}

function AgentCalendarView({ items, runs }) {
  return <ResourceView title="Agent Calendar" description="Track scheduled agent runs, next execution windows, and approval pressure before it becomes operational drag."><Row gutter={[12, 12]}>{items.map((item) => <Col xs={24} lg={12} key={item.id}><Card title={item.title} extra={<Tag color={statusColor[item.lastRunStatus || item.status]}>{item.lastRunStatus || item.status}</Tag>}><Space direction="vertical" size={6}><Text>Next run: {item.nextRunAt ? dayjs(item.nextRunAt).format('DD MMM YYYY, HH:mm') : 'Not scheduled'}</Text><Text>Pending approvals: {item.pendingApprovals || 0}</Text><Text>Estimated budget: {item.estimatedCost?.currency || 'NGN'} {item.estimatedCost?.amount || 0}</Text></Space></Card></Col>)}</Row><Card title="Recent scheduled runs"><Table rowKey="_id" dataSource={runs.filter((run) => run.trigger === 'schedule')} pagination={false} columns={[{ title: 'Agent', dataIndex: 'agent', render: (value) => value?.name || value }, { title: 'Status', dataIndex: 'status', render: (value) => <Tag color={statusColor[value]}>{value}</Tag> }, { title: 'Started', dataIndex: 'startedAt', render: (value) => value ? dayjs(value).format('DD MMM, HH:mm') : '-' }]} /></Card></ResourceView>;
}

function KnowledgeView({ items, reload }) {
  const add = () => Modal.confirm({ title: 'Add knowledge source', content: <KnowledgeForm onDone={reload}/>, footer: null, width: 560, icon: null });
  return <ResourceView title="Knowledge" description="Ground agents in tenant ERP records, uploaded files, and compliant public websites." action={<Button type="primary" icon={<PlusOutlined/>} onClick={add}>Add source</Button>}><Table rowKey="_id" dataSource={items} columns={[{ title: 'Source', render: (_, item) => <Space><BookOutlined/><div><Text strong>{item.name}</Text><br/><Text type="secondary">{item.type}</Text></div></Space> }, { title: 'Status', dataIndex: 'status', render: (value) => <Tag color={statusColor[value]}>{value}</Tag> }, { title: 'Documents', dataIndex: 'documentCount' }, { title: 'Chunks', dataIndex: 'chunkCount' }, { title: 'Last refreshed', dataIndex: 'lastIngestedAt', render: (value) => value ? dayjs(value).fromNow?.() || dayjs(value).format('DD MMM') : 'Not ingested' }]}/></ResourceView>;
}
function KnowledgeForm({ onDone }) { const [form] = Form.useForm(); const submit = async () => { const values = await form.validateFields(); await request.create({ entity: 'knowledgesource', jsonData: { ...values, status: 'draft', config: values.type === 'website' ? { url: values.url } : { entity: values.entity } } }); Modal.destroyAll(); onDone(); message.success('Knowledge source added'); }; return <Form form={form} layout="vertical"><Form.Item name="name" label="Name" rules={[{ required: true }]}><Input/></Form.Item><Form.Item name="type" label="Source type" rules={[{ required: true }]}><Select options={[{ value: 'erp', label: 'ERP records' }, { value: 'file', label: 'Uploaded file' }, { value: 'website', label: 'Approved website' }]}/></Form.Item><Form.Item name="url" label="Public URL"><Input placeholder="https://example.com"/></Form.Item><Form.Item name="entity" label="ERP entity"><Select options={['Lead','Contact','Company','Campaign','Expense'].map((value) => ({ value, label: value }))}/></Form.Item><Button type="primary" onClick={submit}>Add source</Button></Form>; }

function ToolsView({ tools }) { return <ResourceView title="Tools" description="Capabilities are permission checked at execution time. High-risk tools always require approval."><Row gutter={[12,12]}>{tools.map((item) => <Col xs={24} md={12} xl={8} key={item.key}><Card size="small"><Space align="start"><ApiOutlined className="agent-template-icon"/><div><Text strong>{item.label}</Text><Paragraph type="secondary">{item.key}</Paragraph><Space><Tag color={riskColor[item.riskLevel]}>{item.riskLevel} risk</Tag><Tag color={item.available ? 'green' : 'default'}>{item.available ? 'Available' : 'Unavailable'}</Tag></Space></div></Space></Card></Col>)}</Row></ResourceView>; }

function BrandView({ items, reload }) { const create = async () => { await request.create({ entity: 'brandprofile', jsonData: { name: 'Primary Brand', voice: 'Clear, confident, practical', audience: 'Business decision makers', vocabulary: ['trusted', 'measurable'], prohibitedClaims: ['guaranteed results'], isDefault: items.length === 0 } }); await reload(); message.success('Brand profile created'); }; return <ResourceView title="Brand Center" description="Give every agent one consistent voice, vocabulary, visual identity, and claim policy." action={<Button type="primary" icon={<PlusOutlined/>} onClick={create}>New brand profile</Button>}><Row gutter={[12,12]}>{items.map((item) => <Col xs={24} lg={12} key={item._id}><Card title={item.name} extra={item.isDefault && <Tag color="green">Default</Tag>}><Descriptions column={1} size="small" items={[{ key: 'voice', label: 'Voice', children: item.voice || '-' }, { key: 'audience', label: 'Audience', children: item.audience || '-' }, { key: 'words', label: 'Vocabulary', children: <Space wrap>{(item.vocabulary || []).map((word) => <Tag key={word}>{word}</Tag>)}</Space> }, { key: 'claims', label: 'Prohibited claims', children: <Space wrap>{(item.prohibitedClaims || []).map((word) => <Tag color="red" key={word}>{word}</Tag>)}</Space> }]}/></Card></Col>)}</Row></ResourceView>; }

function SocialView({ items, reload }) {
  const [mode, setMode] = useState('Calendar');
  const [scheduleOpen, setScheduleOpen] = useState(false);
  const [selectedPost, setSelectedPost] = useState(null);
  const [channelFilter, setChannelFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [form] = Form.useForm();
  const filteredItems = useMemo(() => items.filter((item) => {
    const channels = item.channels?.length ? item.channels : [item.provider];
    const channelOk = channelFilter === 'all' || channels.includes(channelFilter);
    const statusOk = statusFilter === 'all' || item.status === statusFilter || item.approvalStatus === statusFilter;
    return channelOk && statusOk;
  }), [items, channelFilter, statusFilter]);
  const calendarItems = filteredItems.reduce((acc, item) => {
    const key = item.scheduledAt ? dayjs(item.scheduledAt).format('YYYY-MM-DD') : 'draft';
    acc[key] = [...(acc[key] || []), item];
    return acc;
  }, {});
  const metrics = useMemo(() => {
    const byChannel = CHANNELS.reduce((acc, channel) => ({ ...acc, [channel]: 0 }), {});
    let approvals = 0;
    let scheduled = 0;
    let published = 0;
    let failed = 0;
    let engagement = 0;
    let spend = 0;

    for (const item of items) {
      const channels = item.channels?.length ? item.channels : [item.provider];
      channels.forEach((channel) => { byChannel[channel] = (byChannel[channel] || 0) + 1; });
      approvals += item.approvalStatus === 'pending' ? 1 : 0;
      scheduled += item.status === 'scheduled' || item.status === 'pending_approval' ? 1 : 0;
      published += item.status === 'published' ? 1 : 0;
      failed += item.status === 'failed' ? 1 : 0;
      engagement += Number(item.analytics?.engagement || item.analytics?.engagements || 0);
      spend += Number(item.ads?.budget?.amount || item.adBudget?.amount || item.boostBudget || 0);
    }
    return { byChannel, approvals, scheduled, published, failed, engagement, spend };
  }, [items]);
  const upcoming = filteredItems
    .filter((item) => item.scheduledAt && dayjs(item.scheduledAt).isAfter(dayjs().subtract(1, 'hour')))
    .sort((a, b) => dayjs(a.scheduledAt).valueOf() - dayjs(b.scheduledAt).valueOf())
    .slice(0, 6);
  const bestChannel = Object.entries(metrics.byChannel).sort((a, b) => b[1] - a[1])[0]?.[0] || 'linkedin';

  const create = async () => {
    const values = await form.validateFields();
    const channelVariants = {};
    CHANNELS.forEach((channel) => {
      if (values[`${channel}Caption`] || values[`${channel}MediaUrl`]) {
        channelVariants[channel] = {
          caption: values[`${channel}Caption`] || values.caption,
          mediaUrl: values[`${channel}MediaUrl`] || values.mediaUrl,
        };
      }
    });
    await request.post({
      entity: 'social/post/schedule',
      jsonData: {
        caption: values.caption,
        mediaUrl: values.mediaUrl,
        channels: values.channels,
        provider: values.channels?.[0] || 'linkedin',
        timezone: values.timezone || 'Africa/Lagos',
        scheduledAt: values.scheduledAt?.toISOString?.() || values.scheduledAt,
        recurrence: values.recurrence === 'none' ? undefined : { frequency: values.recurrence },
        campaign: values.campaign,
        channelVariants,
        ads: values.adsEnabled ? {
          objective: values.adObjective,
          audience: values.adAudience,
          budget: { amount: values.adBudget || 0, currency: 'NGN' },
          durationDays: values.adDurationDays || 7,
        } : undefined,
        analytics: { impressions: 0, clicks: 0, engagement: 0, conversions: 0 },
      },
    });
    setScheduleOpen(false);
    form.resetFields();
    await reload();
    message.success('Social draft scheduled for approval');
  };
  const approve = async (id) => { await request.post({ entity: `social/post/${id}/approve`, jsonData: {} }); await reload(); };
  const retry = async (id) => { await request.post({ entity: `social/post/${id}/retry`, jsonData: {} }); await reload(); };
  const publish = async (id) => { await request.post({ entity: `social/post/${id}/publish`, jsonData: {} }); await reload(); };
  const reschedule = async (record) => { await request.patch({ entity: `social/post/${record._id}/reschedule`, jsonData: { scheduledAt: dayjs(record.scheduledAt).add(1, 'day').toISOString(), timezone: record.timezone || 'Africa/Lagos' } }); await reload(); };

  const postColumns = [
    {
      title: 'Content',
      render: (_, item) => (
        <Space direction="vertical" size={2} className="social-content-cell">
          <Text strong ellipsis>{item.caption || 'Untitled social post'}</Text>
          <Text type="secondary">{item.mediaUrl ? 'Media attached' : 'Text only'} · {item.timezone || 'Africa/Lagos'}</Text>
        </Space>
      ),
    },
    {
      title: 'Channels',
      render: (_, item) => <ChannelTags channels={item.channels?.length ? item.channels : [item.provider]} />,
    },
    {
      title: 'Schedule',
      dataIndex: 'scheduledAt',
      render: (value) => value ? dayjs(value).format('DD MMM YYYY, HH:mm') : <Text type="secondary">Draft</Text>,
    },
    {
      title: 'Approval',
      dataIndex: 'approvalStatus',
      render: (value) => <Tag color={value === 'approved' ? 'green' : value === 'rejected' ? 'red' : 'orange'}>{value || 'pending'}</Tag>,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      render: (value) => <Tag color={statusColor[value]}>{value}</Tag>,
    },
    {
      title: 'Actions',
      render: (_, record) => (
        <Space wrap>
          <Button size="small" icon={<EyeOutlined />} onClick={() => setSelectedPost(record)}>Review</Button>
          {record.approvalStatus !== 'approved' ? <Button size="small" onClick={() => approve(record._id)}>Approve</Button> : null}
          {record.approvalStatus === 'approved' && record.status !== 'published' ? <Button size="small" icon={<SendOutlined />} onClick={() => publish(record._id)}>Publish</Button> : null}
          <Button size="small" onClick={() => reschedule(record)}>+1 day</Button>
          {record.status === 'failed' ? <Button size="small" danger onClick={() => retry(record._id)}>Retry</Button> : null}
        </Space>
      ),
    },
  ];

  return <ResourceView
    title="Social Media Command Center"
    description="Plan, approve, publish, advertise, and analyze channel-native content across Facebook, Instagram, LinkedIn, X, and WhatsApp Business."
    action={<Space wrap><Segmented value={mode} onChange={setMode} options={['Calendar', 'List', 'Analytics', 'Ads']} /><Button type="primary" icon={<PlusOutlined/>} onClick={() => setScheduleOpen(true)}>Schedule post</Button></Space>}
  >
    <Row gutter={[12, 12]}>
      <Col xs={24} md={6}><Card size="small"><Statistic title="Scheduled queue" value={metrics.scheduled} prefix={<ClockCircleOutlined />} /></Card></Col>
      <Col xs={24} md={6}><Card size="small"><Statistic title="Pending approvals" value={metrics.approvals} prefix={<CheckCircleOutlined />} /></Card></Col>
      <Col xs={24} md={6}><Card size="small"><Statistic title="Published posts" value={metrics.published} prefix={<ShareAltOutlined />} /></Card></Col>
      <Col xs={24} md={6}><Card size="small"><Statistic title="Ad budget planned" value={metrics.spend} prefix="₦" /></Card></Col>
    </Row>

    <Card size="small" className="agent-resource-card">
      <Space wrap style={{ width: '100%', justifyContent: 'space-between' }}>
        <Space wrap>
          <Select value={channelFilter} onChange={setChannelFilter} style={{ width: 180 }} options={[{ value: 'all', label: 'All channels' }, ...CHANNELS.map((value) => ({ value, label: CHANNEL_LABELS[value] }))]} />
          <Select value={statusFilter} onChange={setStatusFilter} style={{ width: 190 }} options={[
            { value: 'all', label: 'All statuses' },
            { value: 'pending', label: 'Pending approval' },
            { value: 'approved', label: 'Approved' },
            { value: 'scheduled', label: 'Scheduled' },
            { value: 'published', label: 'Published' },
            { value: 'failed', label: 'Failed' },
          ]} />
        </Space>
        <Space wrap>
          <Tag color="blue">LinkedIn included</Tag>
          <Tag color="green">Best active channel: {CHANNEL_LABELS[bestChannel]}</Tag>
          <Text type="secondary">{filteredItems.length} visible posts</Text>
        </Space>
      </Space>
    </Card>

    {mode === 'Calendar' ? (
      <Row gutter={[14, 14]} className="agent-resource-card">
        <Col xs={24} xl={16}>
          <Card title="Content calendar">
            <DatePicker.Calendar
              fullscreen={false}
              cellRender={(current) => {
                const list = calendarItems[current.format('YYYY-MM-DD')] || [];
                return <div className="social-calendar-cell">
                  {list.slice(0, 4).map((item) => {
                    const channels = item.channels?.length ? item.channels : [item.provider];
                    return <button key={item._id} className="social-calendar-post" onClick={() => setSelectedPost(item)}>
                      <span style={{ background: CHANNEL_COLORS[channels[0]] }} />
                      <Text ellipsis>{channels.map((channel) => CHANNEL_LABELS[channel]).join(', ')}</Text>
                    </button>;
                  })}
                </div>;
              }}
            />
          </Card>
        </Col>
        <Col xs={24} xl={8}>
          <Card title="Upcoming publishing queue">
            <List
              dataSource={upcoming}
              locale={{ emptyText: 'No upcoming posts match these filters.' }}
              renderItem={(item) => (
                <List.Item actions={[<Button size="small" onClick={() => setSelectedPost(item)}>Open</Button>]}>
                  <List.Item.Meta
                    title={<Space><ChannelTags channels={item.channels?.length ? item.channels : [item.provider]} /><Tag color={statusColor[item.status]}>{item.status}</Tag></Space>}
                    description={<Space direction="vertical" size={0}><Text>{dayjs(item.scheduledAt).format('DD MMM, HH:mm')}</Text><Text type="secondary" ellipsis>{item.caption}</Text></Space>}
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
    ) : null}

    {mode === 'List' ? (
      <Card className="agent-resource-card" title="Scheduled and published posts">
        <Table rowKey="_id" dataSource={filteredItems} columns={postColumns} pagination={{ pageSize: 8 }} />
      </Card>
    ) : null}

    {mode === 'Analytics' ? (
      <Row gutter={[14, 14]} className="agent-resource-card">
        <Col xs={24} lg={15}>
          <Card title="Channel analytics dashboard">
            <Row gutter={[12, 12]}>
              {CHANNELS.map((channel) => {
                const count = metrics.byChannel[channel] || 0;
                const percent = items.length ? Math.round((count / items.length) * 100) : 0;
                return <Col xs={24} sm={12} key={channel}>
                  <div className="social-channel-metric">
                    <Space style={{ width: '100%', justifyContent: 'space-between' }}>
                      <Text strong>{CHANNEL_LABELS[channel]}</Text>
                      <Tag color={CHANNEL_COLORS[channel]}>{count} posts</Tag>
                    </Space>
                    <Progress percent={percent} strokeColor={CHANNEL_COLORS[channel]} />
                  </div>
                </Col>;
              })}
            </Row>
          </Card>
        </Col>
        <Col xs={24} lg={9}>
          <Card title="Performance summary">
            <Space direction="vertical" size={14} style={{ width: '100%' }}>
              <Statistic title="Tracked engagement" value={metrics.engagement} prefix={<LineChartOutlined />} />
              <Statistic title="Failed publications" value={metrics.failed} valueStyle={{ color: metrics.failed ? '#cf1322' : undefined }} />
              <Alert type="info" showIcon message={`Use ${CHANNEL_LABELS[bestChannel]} as your planning baseline, then adapt caption length and CTA per channel.`} />
            </Space>
          </Card>
        </Col>
      </Row>
    ) : null}

    {mode === 'Ads' ? (
      <Row gutter={[14, 14]} className="agent-resource-card">
        <Col xs={24} lg={10}>
          <Card title="Ads management snapshot">
            <Space direction="vertical" size={14} style={{ width: '100%' }}>
              <Statistic title="Planned ad spend" value={metrics.spend} prefix="₦" />
              <Statistic title="Boost-ready posts" value={filteredItems.filter((item) => item.ads || item.adBudget || item.boostBudget).length} />
              <Alert type="warning" showIcon message="Live ad buying should remain approval-controlled. Use this board to plan objectives, audiences, budget, and campaign handoff." />
            </Space>
          </Card>
        </Col>
        <Col xs={24} lg={14}>
          <Card title="Boost and ads plan">
            <Table
              rowKey="_id"
              dataSource={filteredItems.filter((item) => item.ads || item.adBudget || item.boostBudget)}
              pagination={false}
              locale={{ emptyText: 'No posts have ad planning fields yet. Schedule a post and enable boost planning.' }}
              columns={[
                { title: 'Post', dataIndex: 'caption', ellipsis: true },
                { title: 'Channels', render: (_, item) => <ChannelTags channels={item.channels?.length ? item.channels : [item.provider]} /> },
                { title: 'Objective', render: (_, item) => item.ads?.objective || item.adObjective || 'Awareness' },
                { title: 'Audience', render: (_, item) => item.ads?.audience || item.adAudience || 'Not set' },
                { title: 'Budget', render: (_, item) => `₦${Number(item.ads?.budget?.amount || item.adBudget?.amount || item.boostBudget || 0).toLocaleString()}` },
              ]}
            />
          </Card>
        </Col>
      </Row>
    ) : null}

    <Drawer title="Social post review" open={Boolean(selectedPost)} onClose={() => setSelectedPost(null)} width={640}>
      {selectedPost ? <SocialPostDetail post={selectedPost} approve={approve} publish={publish} retry={retry} reschedule={reschedule} /> : null}
    </Drawer>

    <Modal open={scheduleOpen} onCancel={() => setScheduleOpen(false)} onOk={create} title="Schedule social post" width={760}>
      <Form form={form} layout="vertical" initialValues={{ channels: ['linkedin'], timezone: 'Africa/Lagos', scheduledAt: dayjs().add(1, 'day'), recurrence: 'none', adsEnabled: false, adObjective: 'lead_generation', adDurationDays: 7 }}>
        <Row gutter={12}>
          <Col xs={24} md={16}>
            <Form.Item name="caption" label="Master caption" rules={[{ required: true }]}>
              <Input.TextArea rows={5} placeholder="Write the main message. You can override it per channel below." />
            </Form.Item>
          </Col>
          <Col xs={24} md={8}>
            <Form.Item name="channels" label="Channels" rules={[{ required: true }]}>
              <Select mode="multiple" options={CHANNELS.map((value) => ({ value, label: CHANNEL_LABELS[value] }))} />
            </Form.Item>
            <Form.Item name="scheduledAt" label="Publish time" rules={[{ required: true }]}>
              <DatePicker showTime style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item name="timezone" label="Timezone"><Input /></Form.Item>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col xs={24} md={12}><Form.Item name="mediaUrl" label="Default media URL"><Input placeholder="https://..." /></Form.Item></Col>
          <Col xs={24} md={12}><Form.Item name="recurrence" label="Recurrence"><Select options={[{ value: 'none', label: 'No recurrence' }, { value: 'daily', label: 'Daily' }, { value: 'weekly', label: 'Weekly' }, { value: 'monthly', label: 'Monthly' }]} /></Form.Item></Col>
        </Row>
        <Tabs
          size="small"
          items={CHANNELS.map((channel) => ({
            key: channel,
            label: CHANNEL_LABELS[channel],
            children: <Row gutter={12}>
              <Col xs={24} md={16}><Form.Item name={`${channel}Caption`} label={`${CHANNEL_LABELS[channel]} caption override`}><Input.TextArea rows={3} placeholder={`Optional ${CHANNEL_LABELS[channel]}-specific version`} /></Form.Item></Col>
              <Col xs={24} md={8}><Form.Item name={`${channel}MediaUrl`} label="Media override"><Input placeholder="https://..." /></Form.Item></Col>
            </Row>,
          }))}
        />
        <Card size="small" title={<Space><FundProjectionScreenOutlined />Ads and boost planning</Space>}>
          <Row gutter={12}>
            <Col xs={24} md={6}><Form.Item name="adsEnabled" label="Plan boost" valuePropName="checked"><Switch /></Form.Item></Col>
            <Col xs={24} md={6}><Form.Item name="adObjective" label="Objective"><Select options={[{ value: 'awareness', label: 'Awareness' }, { value: 'engagement', label: 'Engagement' }, { value: 'lead_generation', label: 'Lead generation' }, { value: 'traffic', label: 'Traffic' }]} /></Form.Item></Col>
            <Col xs={24} md={6}><Form.Item name="adBudget" label="Budget (NGN)"><InputNumber min={0} style={{ width: '100%' }} /></Form.Item></Col>
            <Col xs={24} md={6}><Form.Item name="adDurationDays" label="Duration days"><InputNumber min={1} style={{ width: '100%' }} /></Form.Item></Col>
            <Col xs={24}><Form.Item name="adAudience" label="Audience"><Input placeholder="Warm leads, Lagos SMEs, website visitors..." /></Form.Item></Col>
          </Row>
        </Card>
      </Form>
    </Modal>
  </ResourceView>;
}

function ChannelTags({ channels = [] }) {
  return <Space wrap>{channels.map((value) => <Tag key={value} color={CHANNEL_COLORS[value] || 'default'}>{CHANNEL_LABELS[value] || value}</Tag>)}</Space>;
}

function SocialPostDetail({ post, approve, publish, retry, reschedule }) {
  const channels = post.channels?.length ? post.channels : [post.provider];
  return <Space direction="vertical" size={16} style={{ width: '100%' }}>
    <Space wrap>
      <Tag color={statusColor[post.status]}>{post.status}</Tag>
      <Tag color={post.approvalStatus === 'approved' ? 'green' : 'orange'}>{post.approvalStatus || 'pending'}</Tag>
      <ChannelTags channels={channels} />
    </Space>
    <Card size="small" title="Master content">
      <Paragraph>{post.caption || 'No caption provided.'}</Paragraph>
      {post.mediaUrl ? <Text copyable>{post.mediaUrl}</Text> : <Text type="secondary">No media URL attached.</Text>}
    </Card>
    <Card size="small" title="Channel variants">
      <Tabs
        size="small"
        items={channels.map((channel) => {
          const variant = post.channelVariants?.[channel] || {};
          return {
            key: channel,
            label: CHANNEL_LABELS[channel],
            children: <Space direction="vertical" size={8} style={{ width: '100%' }}>
              <Paragraph>{variant.caption || post.caption || 'No caption for this channel.'}</Paragraph>
              <Text type="secondary">{String(variant.caption || post.caption || '').length} characters</Text>
              {variant.mediaUrl || post.mediaUrl ? <Text copyable>{variant.mediaUrl || post.mediaUrl}</Text> : null}
            </Space>,
          };
        })}
      />
    </Card>
    <Descriptions bordered size="small" column={1} items={[
      { key: 'scheduled', label: 'Scheduled', children: post.scheduledAt ? dayjs(post.scheduledAt).format('DD MMM YYYY, HH:mm') : 'Draft' },
      { key: 'timezone', label: 'Timezone', children: post.timezone || 'Africa/Lagos' },
      { key: 'recurrence', label: 'Recurrence', children: post.recurrence?.frequency || 'None' },
      { key: 'ad', label: 'Ads plan', children: post.ads ? `${post.ads.objective || 'Awareness'} · ₦${Number(post.ads.budget?.amount || 0).toLocaleString()} · ${post.ads.audience || 'Audience not set'}` : 'No boost plan' },
    ]} />
    <Card size="small" title="Publication attempts">
      <List
        size="small"
        dataSource={post.publicationAttempts || []}
        locale={{ emptyText: 'No publication attempts yet.' }}
        renderItem={(item) => <List.Item><Space direction="vertical" size={0}><Text strong>{CHANNEL_LABELS[item.provider] || item.provider}</Text><Text type="secondary">{item.status} {item.error ? `- ${item.error}` : ''}</Text></Space></List.Item>}
      />
    </Card>
    <Space wrap>
      {post.approvalStatus !== 'approved' ? <Button type="primary" onClick={() => approve(post._id)}>Approve</Button> : null}
      {post.approvalStatus === 'approved' && post.status !== 'published' ? <Button type="primary" icon={<SendOutlined />} onClick={() => publish(post._id)}>Publish now</Button> : null}
      <Button onClick={() => reschedule(post)}>Reschedule +1 day</Button>
      {post.status === 'failed' ? <Button danger onClick={() => retry(post._id)}>Retry failed post</Button> : null}
    </Space>
  </Space>;
}

function BudgetsView({ items, money, reload }) { const create = async () => { await request.create({ entity: 'agentbudget', jsonData: { name: 'Growth Agent Budget', allocated: { amount: 250000, currency: 'NGN' }, actual: { amount: 0, currency: 'NGN' }, approvalThreshold: { amount: 50000, currency: 'NGN' }, status: 'active' } }); await reload(); message.success('Agent budget created'); }; return <ResourceView title="Agent Budgets" description="Control NGN allocation, provider usage, channel spend, and approval thresholds." action={<Button type="primary" icon={<PlusOutlined/>} onClick={create}>Create budget</Button>}><Row gutter={[12,12]}>{items.map((item) => { const pct = item.allocated?.amount ? Math.round((item.actual?.amount || 0) / item.allocated.amount * 100) : 0; return <Col xs={24} lg={12} key={item._id}><Card title={item.name} extra={<Tag color={statusColor[item.status]}>{item.status}</Tag>}><Row gutter={12}><Col span={8}><Statistic title="Allocated" value={money.moneyFormatter({ amount: item.allocated?.amount || 0, currency_code: 'NGN' })}/></Col><Col span={8}><Statistic title="Actual" value={money.moneyFormatter({ amount: item.actual?.amount || 0, currency_code: 'NGN' })}/></Col><Col span={8}><Statistic title="Remaining" value={money.moneyFormatter({ amount: Math.max(0,(item.allocated?.amount || 0)-(item.actual?.amount || 0)), currency_code: 'NGN' })}/></Col></Row><Progress percent={pct} status={pct > 90 ? 'exception' : 'active'}/><Text type="secondary">Changes above {money.moneyFormatter({ amount: item.approvalThreshold?.amount || 0, currency_code: 'NGN' })} require approval.</Text></Card></Col>; })}</Row></ResourceView>; }

function ProvidersView({ items, reload, currentAdmin }) {
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [selectedProvider, setSelectedProvider] = useState(null);
  const [form] = Form.useForm();
  const canEdit = canAccessPermission(currentAdmin, 'automations.integrationaccount.update');

  const openProvider = (provider) => {
    setSelectedProvider(provider);
    form.resetFields();
    const publicValues = provider.account?.publicConfig || {};
    const nextValues = { name: provider.account?.name || provider.label, enabled: provider.account?.enabled ?? true };
    for (const field of provider.publicFields || []) nextValues[field.key] = publicValues[field.key];
    form.setFieldsValue(nextValues);
    setDrawerOpen(true);
  };

  const saveProvider = async () => {
    const values = await form.validateFields();
    if (!selectedProvider) return;
    const publicConfig = {};
    const secretConfig = {};
    for (const field of selectedProvider.publicFields || []) if (values[field.key]) publicConfig[field.key] = values[field.key];
    for (const field of selectedProvider.secretFields || []) if (values[field.key]) secretConfig[field.key] = values[field.key];

    const accountId = selectedProvider.account?._id;
    const payload = {
      provider: selectedProvider.key,
      name: values.name || selectedProvider.label,
      enabled: values.enabled,
      status: values.enabled ? 'active' : 'disabled',
      publicConfig,
      ...(Object.keys(secretConfig).length ? { secretConfig } : {}),
    };

    if (accountId) {
      await request.update({ entity: 'integrationaccount', id: accountId, jsonData: payload });
    } else {
      await request.create({ entity: 'integrationaccount', jsonData: payload });
    }
    await reload();
    setDrawerOpen(false);
    message.success('Provider account saved');
  };

  const testProvider = async (providerKey) => {
    await request.post({ entity: `integrationaccount/test/${providerKey}`, jsonData: {} });
    await reload();
  };

  const removeSecret = async (providerKey) => {
    await request.post({ entity: `integrationaccount/secret/${providerKey}`, jsonData: {} });
    await reload();
    message.success('Stored secret removed');
  };

  return <ResourceView title="Provider Accounts" description="Admins can connect LLM, email, and social providers here. Secrets are stored encrypted and only shown back as masked status.">
    <Row gutter={[12, 12]}>
      {items.map((provider) => (
        <Col xs={24} md={12} xl={8} key={provider.key}>
          <Card
            title={provider.label}
            extra={<Tag color={provider.account?.status === 'active' ? 'green' : provider.account?.status === 'error' ? 'red' : 'default'}>{provider.account?.status || 'not configured'}</Tag>}
            actions={[
              <Button type="link" onClick={() => openProvider(provider)} disabled={!canEdit}>Configure</Button>,
              <Button type="link" onClick={() => testProvider(provider.key)} disabled={!provider.account}>Test</Button>,
              <Button type="link" danger onClick={() => removeSecret(provider.key)} disabled={!provider.account?.secretConfigured}>Clear secret</Button>,
            ]}
          >
            <Space direction="vertical" size={10} style={{ width: '100%' }}>
              <Space wrap>
                <Tag>{provider.category}</Tag>
                {provider.supportsLiveTest ? <Tag color="blue">Live test</Tag> : <Tag>Saved only</Tag>}
                {provider.envFallbackActive ? <Tag color="gold">Env fallback</Tag> : null}
              </Space>
              <Text type="secondary">
                {provider.account?.lastTestMessage || 'No connection test has been run yet.'}
              </Text>
              <List
                size="small"
                dataSource={provider.account?.secretPreview || []}
                locale={{ emptyText: 'No stored secret yet' }}
                renderItem={(item) => (
                  <List.Item>
                    <Space direction="vertical" size={0}>
                      <Text strong>{item.key}</Text>
                      <Text type="secondary">{item.maskedValue}</Text>
                    </Space>
                  </List.Item>
                )}
              />
            </Space>
          </Card>
        </Col>
      ))}
    </Row>
    <Drawer
      title={selectedProvider ? `${selectedProvider.label} Provider Account` : 'Provider Account'}
      open={drawerOpen}
      width={520}
      onClose={() => setDrawerOpen(false)}
      extra={<Space><Button onClick={() => setDrawerOpen(false)}>Cancel</Button><Button type="primary" onClick={saveProvider} disabled={!canEdit}>Save</Button></Space>}
    >
      {selectedProvider ? <Form form={form} layout="vertical">
        <Form.Item name="name" label="Account name" rules={[{ required: true }]}><Input /></Form.Item>
        <Form.Item name="enabled" label="Enabled" valuePropName="checked"><Switch /></Form.Item>
        {(selectedProvider.publicFields || []).map((field) => (
          <Form.Item key={field.key} name={field.key} label={field.label}>
            <Input placeholder={field.placeholder} />
          </Form.Item>
        ))}
        <Divider>Secret credentials</Divider>
        <Alert type="info" showIcon message="Secrets are stored encrypted on the server and only returned to the UI as masked previews." style={{ marginBottom: 16 }} />
        {(selectedProvider.secretFields || []).map((field) => (
          <Form.Item key={field.key} name={field.key} label={field.label} extra="Leave blank to keep the current stored secret.">
            <Input.Password placeholder={`Enter ${field.label.toLowerCase()}`} />
          </Form.Item>
        ))}
      </Form> : null}
    </Drawer>
  </ResourceView>;
}

function ResourceView({ title, description, action, children }) { return <Space direction="vertical" size={18} style={{ width:'100%' }}><div className="agent-view-heading"><div><Title level={3}>{title}</Title><Paragraph type="secondary">{description}</Paragraph></div>{action}</div>{children}</Space>; }

function DocGeneratorView({ docTemplates, docTemplateId, setDocTemplateId, docPrompt, setDocPrompt, docRecipient, setDocRecipient, docSendEmail, setDocSendEmail, docResult, docBusy, generateDocument, reload }) {
  const [createOpen, setCreateOpen] = useState(false);
  const [createForm] = Form.useForm();

  const saveTemplate = async () => {
    const values = await createForm.validateFields();
    await request.create({ entity: 'documenttemplate', jsonData: values });
    setCreateOpen(false); createForm.resetFields(); await reload(); message.success('Template saved');
  };

  const selectedTemplate = docTemplates.find((t) => t._id === docTemplateId);
  const typeColor = { invoice: '#1677ff', receipt: '#52c41a', quote: '#fa8c16', contract: '#722ed1', other: '#595959' };

  return (
    <Space direction="vertical" size={20} style={{ width: '100%' }}>
      <div className="agent-view-heading">
        <div>
          <Title level={3}>AI Document Generator</Title>
          <Paragraph type="secondary">Describe what you need in plain English. The AI will extract client details, amounts, and line items — then compile a ready-to-send document.</Paragraph>
        </div>
        <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>New Template</Button>
      </div>

      {/* Template Gallery */}
      <Card title="Document Templates" extra={<Text type="secondary">{docTemplates.length} templates</Text>}>
        {docTemplates.length === 0 ? <Empty description="No templates yet. Create one to get started." /> : (
          <Row gutter={[12, 12]}>
            {docTemplates.map((tpl) => (
              <Col xs={24} sm={12} md={8} xl={6} key={tpl._id}>
                <Card
                  hoverable
                  size="small"
                  style={{ border: docTemplateId === tpl._id ? `2px solid ${typeColor[tpl.type] || '#1677ff'}` : '1px solid #e2e8f0', borderRadius: 8 }}
                  onClick={() => setDocTemplateId(docTemplateId === tpl._id ? null : tpl._id)}
                >
                  <Space direction="vertical" size={4} style={{ width: '100%' }}>
                    <Space>
                      <FileTextOutlined style={{ fontSize: 20, color: typeColor[tpl.type] || '#1677ff' }} />
                      <Text strong>{tpl.name}</Text>
                    </Space>
                    <Tag color={typeColor[tpl.type] || 'default'}>{tpl.type}</Tag>
                    <Text type="secondary" style={{ fontSize: 12 }}>{tpl.description || 'No description'}</Text>
                    <Space wrap style={{ marginTop: 4 }}>
                      {(tpl.fields || []).slice(0, 4).map((f) => <Tag key={f} style={{ fontSize: 11 }}>{f}</Tag>)}
                      {(tpl.fields || []).length > 4 && <Tag style={{ fontSize: 11 }}>+{tpl.fields.length - 4} more</Tag>}
                    </Space>
                  </Space>
                </Card>
              </Col>
            ))}
          </Row>
        )}
      </Card>

      {/* Generation Panel */}
      <Row gutter={16}>
        <Col xs={24} lg={12}>
          <Card title={<Space><RobotOutlined />Generate Document</Space>}
            extra={selectedTemplate && <Tag color={typeColor[selectedTemplate.type]}>{selectedTemplate.name}</Tag>}>
            <Space direction="vertical" size={14} style={{ width: '100%' }}>
              <div>
                <Text strong>Describe the document</Text>
                <Paragraph type="secondary" style={{ marginBottom: 6, marginTop: 2, fontSize: 12 }}>
                  Write naturally: e.g. &ldquo;Invoice for a customer at billing@email.com - NGN 45,000 for 3 months of social media management&rdquo;
                </Paragraph>
                <Input.TextArea
                  rows={5}
                  value={docPrompt}
                  onChange={(e) => setDocPrompt(e.target.value)}
                  placeholder="Invoice for a customer - NGN 120,000 for Q3 campaign management services"
                  allowClear
                />
              </div>
              <div>
                <Text strong>Recipient email (optional)</Text>
                <Input
                  prefix={<MailOutlined style={{ color: '#94a3b8' }} />}
                  value={docRecipient}
                  onChange={(e) => setDocRecipient(e.target.value)}
                  placeholder="client@company.com"
                  style={{ marginTop: 6 }}
                />
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <Switch checked={docSendEmail} onChange={setDocSendEmail} id="doc-send-email-toggle" />
                <Text>Send document via email after generation</Text>
              </div>
              <Button
                type="primary"
                block
                size="large"
                icon={<SendOutlined />}
                loading={docBusy}
                onClick={generateDocument}
              >
                Generate {selectedTemplate ? selectedTemplate.type : 'document'}
              </Button>
            </Space>
          </Card>
        </Col>

        <Col xs={24} lg={12}>
          <Card
            title={<Space><EyeOutlined />Preview</Space>}
            extra={docResult?.pdfFileName ? <Button size="small" icon={<DownloadOutlined />}>Download PDF</Button> : null}
            style={{ height: '100%' }}
          >
            {!docResult && !docBusy && (
              <Empty
                image={<FileTextOutlined style={{ fontSize: 48, color: '#d9d9d9' }} />}
                description="Your generated document will appear here"
              />
            )}
            {docBusy && <div style={{ textAlign: 'center', padding: 40 }}><Spin size="large" /><br/><Text type="secondary" style={{ marginTop: 12, display: 'block' }}>AI is extracting fields and compiling your document…</Text></div>}
            {docResult && !docBusy && (
              <Space direction="vertical" size={14} style={{ width: '100%' }}>
                {/* Extracted fields */}
                <Card size="small" title="Extracted fields" style={{ background: '#f8fafc', border: '1px solid #e2e8f0' }}>
                  <Descriptions size="small" column={2}>
                    {Object.entries(docResult.extractedFields || {}).filter(([, v]) => v && !Array.isArray(v)).map(([k, v]) => (
                      <Descriptions.Item key={k} label={k.replace(/([A-Z])/g, ' $1').replace(/^./, (s) => s.toUpperCase())}>
                        {String(v)}
                      </Descriptions.Item>
                    ))}
                  </Descriptions>
                  {(docResult.extractedFields?.items || []).length > 0 && (
                    <Table
                      size="small"
                      rowKey="description"
                      pagination={false}
                      style={{ marginTop: 8 }}
                      dataSource={docResult.extractedFields.items}
                      columns={[
                        { title: 'Item', dataIndex: 'description' },
                        { title: 'Qty', dataIndex: 'qty', width: 60 },
                        { title: 'Price', dataIndex: 'price', width: 90 },
                        { title: 'Total', render: (_, r) => (r.qty || 1) * (r.price || 0), width: 90 },
                      ]}
                    />
                  )}
                </Card>

                {/* Email status */}
                {docResult.emailResult && (
                  <Alert
                    type={docResult.emailResult.error ? 'error' : 'success'}
                    showIcon
                    message={docResult.emailResult.error ? `Email failed: ${docResult.emailResult.error}` : `Email sent to ${(docResult.emailResult.accepted || []).join(', ')}`}
                  />
                )}

                {/* HTML preview */}
                <Card size="small" title="Document preview" bodyStyle={{ padding: 0 }}>
                  <div
                    style={{ maxHeight: 400, overflow: 'auto', border: '1px solid #e2e8f0', borderRadius: 6 }}
                    // eslint-disable-next-line react/no-danger
                    dangerouslySetInnerHTML={{ __html: docResult.compiledHtml || '' }}
                  />
                </Card>
              </Space>
            )}
          </Card>
        </Col>
      </Row>

      {/* Create Template Drawer */}
      <Drawer
        title="Create Document Template"
        open={createOpen}
        width={520}
        onClose={() => { setCreateOpen(false); createForm.resetFields(); }}
        extra={<Space><Button onClick={() => setCreateOpen(false)}>Cancel</Button><Button type="primary" onClick={saveTemplate}>Save template</Button></Space>}
      >
        <Form form={createForm} layout="vertical">
          <Form.Item name="name" label="Template name" rules={[{ required: true }]}>
            <Input placeholder="Standard Invoice" />
          </Form.Item>
          <Form.Item name="type" label="Document type" rules={[{ required: true }]}>
            <Select options={['invoice', 'receipt', 'quote', 'contract', 'other'].map((v) => ({ value: v, label: v.charAt(0).toUpperCase() + v.slice(1) }))} />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea rows={2} placeholder="Describe when this template is used" />
          </Form.Item>
          <Form.Item name="accentColor" label="Accent colour" initialValue="#1677ff">
            <Input placeholder="#1677ff" />
          </Form.Item>
          <Form.Item name="footerText" label="Footer text" initialValue="Thank you for your business.">
            <Input />
          </Form.Item>
          <Form.Item name="fields" label="Expected fields" help="Fields the AI will extract from the prompt">
            <Select mode="tags" placeholder="clientName, total, items..." />
          </Form.Item>
        </Form>
      </Drawer>
    </Space>
  );
}
