import React from 'react';
import { useCurrentFrame, spring, useVideoConfig, interpolate } from 'remotion';
import { COLORS, FONT, GLASS_CARD, SPRING } from '../styles/theme';
import { MeshBackground } from '../components/MeshBackground';
import { ParticleField } from '../components/ParticleField';
import { FlipCounter, KineticText } from '../components/KineticText';
import { GlassCard } from '../components/GlassCard';

/* ─── Tool data ─── */
const toolNames = [
  'GoHighLevel', 'Google Ads', 'Meta Ads', 'Twilio', 'n8n', 'Stripe',
  'HubSpot', 'Calendly', 'Mailchimp', 'ServiceTitan', 'Zendesk', 'Close',
  'Pipedrive', 'Trello', 'Gusto', 'Rippling', 'Toast', 'QuickBooks',
  'Slack', 'GitHub', 'Notion', 'Supabase', 'Salesforce', 'Shopify',
  'Freshdesk', 'Monday', 'Asana', 'Jira', 'Linear', 'Intercom',
];

const toolColors = [
  '#ff6d5a', '#4285f4', '#1877f2', '#f22f46', '#ea5515', '#635bff',
  '#ff7a59', '#006bff', '#ffe01b', '#f77f00', '#03363d', '#5055e8',
  '#21313c', '#0079bf', '#ff5e57', '#24a148', '#ff6600', '#2ca01c',
  '#e01e5a', '#24292e', '#787878', '#3ecf8e', '#00a1e0', '#7ab55c',
  '#25c16f', '#f04095', '#fc636b', '#0065ff', '#5e6ad2', '#286efa',
];

/* ─── Hex / honeycomb layout calculator ─── */
const COLS = 6;
const CARD_W = 220;
const CARD_H = 56;
const GAP_X = 18;
const GAP_Y = 14;
const GRID_TOP = 310;

const getHexPos = (index: number) => {
  const row = Math.floor(index / COLS);
  const col = index % COLS;
  const isOffsetRow = row % 2 === 1;
  const totalGridW = COLS * (CARD_W + GAP_X) - GAP_X;
  const gridLeft = (1920 - totalGridW) / 2;

  const x = gridLeft + col * (CARD_W + GAP_X) + (isOffsetRow ? (CARD_W + GAP_X) / 2 : 0);
  const y = GRID_TOP + row * (CARD_H + GAP_Y);
  return { x, y, row, col };
};

/* ─── Distance from grid center for radial wave ─── */
const CENTER_ROW = 2.5;
const CENTER_COL = 2.5;

const getDistFromCenter = (index: number) => {
  const row = Math.floor(index / COLS);
  const col = index % COLS;
  return Math.sqrt((row - CENTER_ROW) ** 2 + (col - CENTER_COL) ** 2);
};

/* ─── Honeycomb SVG background ─── */
const HoneycombBg: React.FC = () => {
  const frame = useCurrentFrame();
  const opacity = interpolate(frame, [0, 40], [0, 0.04], {
    extrapolateLeft: 'clamp',
    extrapolateRight: 'clamp',
  });

  // Hexagon path (pointy-top)
  const hexSize = 40;
  const hexH = hexSize * Math.sqrt(3);
  const cols = 30;
  const rows = 18;

  const hexPoints = (cx: number, cy: number) => {
    const pts: string[] = [];
    for (let a = 0; a < 6; a++) {
      const angle = (Math.PI / 3) * a - Math.PI / 6;
      pts.push(`${cx + hexSize * Math.cos(angle)},${cy + hexSize * Math.sin(angle)}`);
    }
    return pts.join(' ');
  };

  return (
    <svg
      style={{
        position: 'absolute',
        top: 0,
        left: 0,
        width: 1920,
        height: 1080,
        opacity,
        pointerEvents: 'none',
      }}
    >
      {Array.from({ length: rows }).map((_, r) =>
        Array.from({ length: cols }).map((_, c) => {
          const cx = c * hexSize * 1.5 + (r % 2 === 0 ? 0 : hexSize * 0.75);
          const cy = r * hexH * 0.5;
          return (
            <polygon
              key={`${r}-${c}`}
              points={hexPoints(cx, cy)}
              fill="none"
              stroke={COLORS.white}
              strokeWidth={0.5}
            />
          );
        })
      )}
    </svg>
  );
};

/* ─── Scan line effect ─── */
const ScanLine: React.FC = () => {
  const frame = useCurrentFrame();
  const scanStart = 100;
  const scanDuration = 120;

  if (frame < scanStart) return null;

  const y = interpolate(frame - scanStart, [0, scanDuration], [GRID_TOP - 20, GRID_TOP + 420], {
    extrapolateLeft: 'clamp',
    extrapolateRight: 'clamp',
  });

  const opacity = interpolate(frame - scanStart, [0, 10, scanDuration - 10, scanDuration], [0, 0.4, 0.4, 0], {
    extrapolateLeft: 'clamp',
    extrapolateRight: 'clamp',
  });

  return (
    <div
      style={{
        position: 'absolute',
        left: 100,
        right: 100,
        top: y,
        height: 3,
        background: `linear-gradient(90deg, transparent, ${COLORS.primary}, ${COLORS.accent}, ${COLORS.primary}, transparent)`,
        opacity,
        boxShadow: `0 0 20px ${COLORS.primary}60, 0 0 40px ${COLORS.primary}30`,
        borderRadius: 2,
        pointerEvents: 'none',
      }}
    />
  );
};

/* ─── Spring config selector for variety ─── */
const springConfigs = [SPRING.snappy, SPRING.smooth, SPRING.bouncy, SPRING.gentle, SPRING.heavy];

/* ─── Main Scene ─── */
export const Scene5McpTools: React.FC = () => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();

  /* Counter section fade-in */
  const counterOpacity = interpolate(frame, [0, 20], [0, 1], {
    extrapolateLeft: 'clamp',
    extrapolateRight: 'clamp',
  });

  return (
    <div
      style={{
        width: 1920,
        height: 1080,
        fontFamily: FONT,
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      <MeshBackground
        color1={COLORS.primary}
        color2={COLORS.secondary}
        color3={COLORS.accent}
        intensity={0.12}
        speed={0.5}
      />

      <HoneycombBg />

      <ParticleField count={40} color={COLORS.white} drift="up" seed={99} />

      {/* ─── Counter Row ─── */}
      <div
        style={{
          position: 'absolute',
          top: 55,
          width: '100%',
          display: 'flex',
          justifyContent: 'center',
          gap: 80,
          opacity: counterOpacity,
        }}
      >
        {/* MCP Tools counter */}
        <div style={{ textAlign: 'center' }}>
          <FlipCounter
            value={240}
            suffix="+"
            fontSize={72}
            color={COLORS.primary}
            startDelay={5}
            duration={70}
          />
          <div style={{ fontSize: 22, color: COLORS.gray, marginTop: 6, fontWeight: 500 }}>
            MCP Tools
          </div>
        </div>

        {/* MCP Servers counter */}
        <div style={{ textAlign: 'center' }}>
          <FlipCounter
            value={30}
            suffix="+"
            fontSize={72}
            color={COLORS.secondary}
            startDelay={15}
            duration={60}
          />
          <div style={{ fontSize: 22, color: COLORS.gray, marginTop: 6, fontWeight: 500 }}>
            MCP Servers
          </div>
        </div>

        {/* Autonomous + Human in The Loop */}
        <div style={{ textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <KineticText
            text="Autonomous + Human in The Loop"
            fontSize={72}
            fontWeight={800}
            color={COLORS.green}
            startDelay={30}
            staggerFrames={5}
            animationType="blur"
          />
        </div>
      </div>

      {/* Divider line */}
      <div
        style={{
          position: 'absolute',
          top: 250,
          left: '50%',
          transform: 'translateX(-50%)',
          width: interpolate(frame, [40, 70], [0, 1200], {
            extrapolateLeft: 'clamp',
            extrapolateRight: 'clamp',
          }),
          height: 1,
          background: `linear-gradient(90deg, transparent, ${COLORS.cardBorder}, transparent)`,
        }}
      />

      {/* Section label */}
      <div
        style={{
          position: 'absolute',
          top: 272,
          width: '100%',
          textAlign: 'center',
          fontSize: 18,
          fontWeight: 500,
          color: COLORS.gray,
          letterSpacing: 3,
          textTransform: 'uppercase',
          opacity: interpolate(frame, [50, 70], [0, 0.6], {
            extrapolateLeft: 'clamp',
            extrapolateRight: 'clamp',
          }),
        }}
      >
        Integrations
      </div>

      {/* ─── Tool Grid: Hex layout with radial wave ─── */}
      {toolNames.map((name, i) => {
        const pos = getHexPos(i);
        const dist = getDistFromCenter(i);

        // Radial wave: center cards first, edges last
        const waveDelay = 55 + dist * 10;

        // Pick varied spring config
        const configIdx = i % springConfigs.length;
        const cardProgress = spring({
          frame: frame - waveDelay,
          fps,
          config: springConfigs[configIdx],
        });

        // Fly in from edges: compute direction from center
        const row = Math.floor(i / COLS);
        const col = i % COLS;
        const dirX = col - CENTER_COL;
        const dirY = row - CENTER_ROW;
        const mag = Math.sqrt(dirX * dirX + dirY * dirY) || 1;
        const flyDist = 300;
        const startX = pos.x + (dirX / mag) * flyDist * (1 - cardProgress);
        const startY = pos.y + (dirY / mag) * flyDist * (1 - cardProgress);

        return (
          <div
            key={i}
            style={{
              position: 'absolute',
              left: startX,
              top: startY,
              width: CARD_W,
              height: CARD_H,
              ...GLASS_CARD,
              borderRadius: 12,
              padding: 0,
              display: 'flex',
              alignItems: 'center',
              opacity: cardProgress,
              overflow: 'hidden',
              borderColor: `${toolColors[i]}20`,
            }}
          >
            {/* Colored left accent bar */}
            <div
              style={{
                width: 4,
                height: '100%',
                background: toolColors[i],
                borderRadius: '12px 0 0 12px',
                flexShrink: 0,
              }}
            />
            <span
              style={{
                fontSize: 14,
                fontWeight: 600,
                color: COLORS.white,
                paddingLeft: 14,
                whiteSpace: 'nowrap',
              }}
            >
              {name}
            </span>
          </div>
        );
      })}

      {/* Scan line */}
      <ScanLine />
    </div>
  );
};
