import { useState } from 'react';
import { Card, Button, Typography, Tag, Space, App } from 'antd';
import {
  VideoCameraOutlined,
  MailOutlined,
  FileTextOutlined,
  CalendarOutlined,
  EnvironmentOutlined,
  TeamOutlined,
  LinkOutlined,
  CheckSquareOutlined,
  CheckCircleFilled,
  RightOutlined,
  ThunderboltOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import type { DashboardActionCampaign, DashboardActionStep, ActionStepKind } from './types';

interface ActionStepsListProps {
  campaign: DashboardActionCampaign;
  onRefresh: () => void;
}

const KIND_ICONS: Record<ActionStepKind, React.ReactNode> = {
  WATCH_VIDEO: <VideoCameraOutlined />,
  SUBMIT_INFLUENCE: <MailOutlined />,
  SIGN_PETITION: <FileTextOutlined />,
  RSVP_EVENT: <CalendarOutlined />,
  SIGNUP_SHIFT: <EnvironmentOutlined />,
  JOIN_CHALLENGE: <TeamOutlined />,
  VISIT_LINK: <LinkOutlined />,
  CUSTOM: <CheckSquareOutlined />,
};

const KIND_LABELS: Record<ActionStepKind, string> = {
  WATCH_VIDEO: 'Watch',
  SUBMIT_INFLUENCE: 'Email',
  SIGN_PETITION: 'Sign',
  RSVP_EVENT: 'RSVP',
  SIGNUP_SHIFT: 'Shift',
  JOIN_CHALLENGE: 'Join',
  VISIT_LINK: 'Visit',
  CUSTOM: 'Action',
};

function resolveStepLink(step: DashboardActionStep): { to: string; external: boolean } | null {
  if (step.targetUrl) {
    const external = /^https?:\/\//i.test(step.targetUrl);
    return { to: step.targetUrl, external };
  }
  if (!step.targetId) return null;
  switch (step.kind) {
    case 'WATCH_VIDEO':
      return { to: `/gallery/watch/${step.targetId}`, external: false };
    case 'SUBMIT_INFLUENCE':
      return { to: `/campaign/${step.targetId}`, external: false };
    case 'SIGN_PETITION':
      return { to: `/petition/${step.targetId}`, external: false };
    case 'RSVP_EVENT':
      return { to: `/event/${step.targetId}`, external: false };
    case 'SIGNUP_SHIFT':
      return { to: `/volunteer/shifts?shiftId=${step.targetId}`, external: false };
    case 'JOIN_CHALLENGE':
      return { to: `/volunteer/challenges/${step.targetId}`, external: false };
    default:
      return null;
  }
}

function HighlightedStep({
  step,
  onNavigate,
  onSelfReport,
  loading,
}: {
  step: DashboardActionStep;
  onNavigate: (step: DashboardActionStep) => void;
  onSelfReport: (step: DashboardActionStep) => void;
  loading: boolean;
}) {
  const isSelfReport = step.kind === 'CUSTOM' || step.kind === 'VISIT_LINK';
  const canNavigate = resolveStepLink(step) !== null;

  return (
    <div
      style={{
        background: 'linear-gradient(135deg, rgba(52,152,219,0.25) 0%, rgba(41,128,185,0.15) 100%)',
        border: '1px solid rgba(52,152,219,0.3)',
        borderRadius: 8,
        padding: '16px 20px',
        margin: '0 0 2px',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
        <ThunderboltOutlined style={{ fontSize: 12, color: '#3498db' }} />
        <Typography.Text strong style={{ fontSize: 12, color: '#3498db', textTransform: 'uppercase', letterSpacing: 0.5 }}>
          Next Up
        </Typography.Text>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
        <div
          style={{
            width: 32,
            height: 32,
            borderRadius: '50%',
            background: 'rgba(52,152,219,0.25)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: 16,
            color: '#3498db',
            flexShrink: 0,
          }}
        >
          {KIND_ICONS[step.kind]}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <Typography.Text strong style={{ fontSize: 15, display: 'block' }}>
            {step.label}
          </Typography.Text>
          {step.description && (
            <Typography.Text type="secondary" style={{ fontSize: 12, display: 'block', marginTop: 2 }}>
              {step.description}
            </Typography.Text>
          )}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
        {isSelfReport ? (
          <>
            {canNavigate && (
              <Button size="middle" onClick={() => onNavigate(step)} icon={<RightOutlined />}>
                Open
              </Button>
            )}
            <Button
              type="primary"
              size="middle"
              loading={loading}
              onClick={() => onSelfReport(step)}
            >
              Mark as done
            </Button>
          </>
        ) : (
          <Button
            type="primary"
            size="middle"
            icon={<RightOutlined />}
            onClick={() => onNavigate(step)}
            disabled={!canNavigate}
          >
            Take Action
          </Button>
        )}
      </div>
    </div>
  );
}

export default function ActionStepsList({ campaign, onRefresh }: ActionStepsListProps) {
  const navigate = useNavigate();
  const { message } = App.useApp();
  const [completingStepId, setCompletingStepId] = useState<string | null>(null);

  const handleSelfReport = async (step: DashboardActionStep) => {
    setCompletingStepId(step.id);
    try {
      await api.post(`/action-campaigns/${campaign.slug}/steps/${step.id}/complete`);
      message.success('Step marked as done');
      onRefresh();
    } catch {
      message.error('Failed to mark step as done');
    } finally {
      setCompletingStepId(null);
    }
  };

  const handleNavigate = (step: DashboardActionStep) => {
    const link = resolveStepLink(step);
    if (!link) return;
    if (link.external) {
      window.open(link.to, '_blank', 'noopener,noreferrer');
    } else {
      navigate(link.to);
    }
  };

  const sortedSteps = [...campaign.steps].sort((a, b) => a.order - b.order);
  const highlightedStep = sortedSteps.find((s) => !s.completed);
  const remainingSteps = sortedSteps.filter((s) => s.id !== highlightedStep?.id);

  return (
    <Card
      styles={{
        header: { borderBottom: '1px solid rgba(255,255,255,0.06)', padding: '12px 20px', minHeight: 'auto' },
        body: { padding: 0 },
      }}
      title={
        <Typography.Text style={{ fontSize: 14, fontWeight: 600 }}>
          {campaign.completedSteps} of {campaign.totalSteps} Actions
        </Typography.Text>
      }
    >
      {highlightedStep && (
        <div style={{ padding: '12px 12px 0' }}>
          <HighlightedStep
            step={highlightedStep}
            onNavigate={handleNavigate}
            onSelfReport={handleSelfReport}
            loading={completingStepId === highlightedStep.id}
          />
        </div>
      )}

      {remainingSteps.map((step, i) => {
        const isSelfReport = step.kind === 'CUSTOM' || step.kind === 'VISIT_LINK';
        const canNavigate = resolveStepLink(step) !== null;

        return (
          <div
            key={step.id}
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              padding: '10px 20px',
              borderTop: (highlightedStep || i > 0) ? '1px solid rgba(255,255,255,0.04)' : undefined,
              opacity: step.completed ? 0.55 : 1,
              gap: 12,
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, flex: 1, minWidth: 0 }}>
              <div
                style={{
                  width: 24,
                  height: 24,
                  borderRadius: '50%',
                  background: step.completed ? '#52c41a' : 'rgba(255,255,255,0.06)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: 12,
                  flexShrink: 0,
                  color: step.completed ? '#fff' : 'rgba(255,255,255,0.5)',
                }}
              >
                {step.completed ? <CheckCircleFilled /> : KIND_ICONS[step.kind]}
              </div>
              <div style={{ minWidth: 0 }}>
                <Typography.Text strong style={{ fontSize: 11, color: 'rgba(255,255,255,0.35)', display: 'block', lineHeight: 1 }}>
                  {KIND_LABELS[step.kind]}
                </Typography.Text>
                <Typography.Text
                  style={{
                    fontSize: 13,
                    display: 'block',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap',
                    textDecoration: step.completed ? 'line-through' : 'none',
                  }}
                >
                  {step.label}
                </Typography.Text>
              </div>
            </div>

            <div style={{ flexShrink: 0 }}>
              {step.completed ? (
                <Tag color="success" style={{ margin: 0, fontSize: 11 }}>Done</Tag>
              ) : isSelfReport ? (
                <Space size={4}>
                  {canNavigate && (
                    <Button size="small" type="text" onClick={() => handleNavigate(step)}>Open</Button>
                  )}
                  <Button
                    size="small"
                    type="primary"
                    loading={completingStepId === step.id}
                    onClick={() => handleSelfReport(step)}
                  >
                    Mark done
                  </Button>
                </Space>
              ) : (
                <Button
                  size="small"
                  type="link"
                  onClick={() => handleNavigate(step)}
                  disabled={!canNavigate}
                  style={{ fontWeight: 600 }}
                >
                  Take Action
                </Button>
              )}
            </div>
          </div>
        );
      })}
    </Card>
  );
}
