import React, { useState, useMemo } from 'react';
import { useApp } from '@modelcontextprotocol/ext-apps/react';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { PageHeader } from '../../components/layout/PageHeader';
import { StatsGrid } from '../../components/layout/StatsGrid';
import { MetricCard } from '../../components/data/MetricCard';
import { SplitLayout } from '../../components/layout/SplitLayout';
import { PieChart } from '../../components/charts/PieChart';
import { BarChart } from '../../components/charts/BarChart';
import '../../styles/base.css';
import '../../styles/interactive.css';

function extractData(result: CallToolResult): any {
  const sc = (result as any).structuredContent;
  if (sc) return sc;
  for (const item of result.content || []) {
    if (item.type === 'text') { try { return JSON.parse(item.text); } catch {} }
  }
  return null;
}

export function App() {
  const [data, setData] = useState<any>((window as any).__MCP_APP_DATA__ || null);

  const { isConnected, error } = useApp({
    appInfo: { name: 'Call Analytics', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (app) => {
      app.ontoolresult = async (result) => {
        const parsed = extractData(result);
        if (parsed) setData(parsed);
      };
    },
  });

  const stats = useMemo(() => {
    if (!data) return null;
    return {
      totalCalls: data.totalCalls ?? data.calls?.length ?? 0,
      avgDuration: data.avgDuration ?? '0:00',
      inbound: data.inbound ?? 0,
      outbound: data.outbound ?? 0,
      completed: data.completed ?? 0,
      noAnswer: data.noAnswer ?? 0,
      busy: data.busy ?? 0,
      failed: data.failed ?? 0,
    };
  }, [data]);

  const peakHours = useMemo(() => {
    if (!data?.peakHours) return [];
    return (data.peakHours || []).map((h: any) => ({
      label: h.hour || h.label || '',
      value: h.count || h.value || 0,
    }));
  }, [data]);

  if (error) return <div className="error-state"><h3>Error</h3><p>{error.message}</p></div>;
  if (!isConnected) return <div className="loading-state"><div className="loading-spinner" /><p>Connecting...</p></div>;
  if (!data) return <div className="loading-state"><div className="loading-spinner" /><p>Waiting for data...</p></div>;

  return (
    <div>
      <PageHeader title="📞 Call Analytics" subtitle="Call metrics and trends" gradient />
      <StatsGrid columns={4}>
        <MetricCard label="Total Calls" value={Number(stats!.totalCalls).toLocaleString()} color="blue" />
        <MetricCard label="Avg Duration" value={String(stats!.avgDuration)} color="purple" />
        <MetricCard label="Inbound" value={Number(stats!.inbound).toLocaleString()} color="green" />
        <MetricCard label="Outbound" value={Number(stats!.outbound).toLocaleString()} color="yellow" />
      </StatsGrid>
      <SplitLayout ratio="50/50" gap="md">
        <PieChart
          title="Direction Breakdown"
          segments={[
            { label: 'Inbound', value: stats!.inbound, color: '#22c55e' },
            { label: 'Outbound', value: stats!.outbound, color: '#6366f1' },
          ]}
          donut
        />
        <PieChart
          title="Call Disposition"
          segments={[
            { label: 'Completed', value: stats!.completed, color: '#22c55e' },
            { label: 'No Answer', value: stats!.noAnswer, color: '#f59e0b' },
            { label: 'Busy', value: stats!.busy, color: '#3b82f6' },
            { label: 'Failed', value: stats!.failed, color: '#ef4444' },
          ]}
        />
      </SplitLayout>
      {peakHours.length > 0 && (
        <BarChart title="Peak Hours" bars={peakHours} orientation="vertical" />
      )}
    </div>
  );
}
