import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Space,
  Typography,
  Button,
  Row,
  Col,
  Spin,
  Tag,
  Modal,
  message,
  Divider,
} from 'antd';
import {
  LikeOutlined,
  LikeFilled,
  EyeOutlined,
  ArrowLeftOutlined,
  PlusOutlined,
  SendOutlined,
} from '@ant-design/icons';
import VideoPlayer from '@/components/media/VideoPlayer';
import ReactionButtons from '@/components/media/ReactionButtons';
import CommentSection from '@/components/media/CommentSection';
import PublicVideoCard from '@/components/media/PublicVideoCard';
import AddToPlaylistModal from '@/components/media/AddToPlaylistModal';
import PublicNavBar from '@/components/PublicNavBar';
import { mediaPublicApi, getOrCreateSessionId } from '@/lib/media-public-api';
import { useAuthStore } from '@/stores/auth.store';
import { useSettingsStore } from '@/stores/settings.store';
import { Link } from 'react-router-dom';
import axios from 'axios';

const { Title, Text } = Typography;

interface Video {
  id: number;
  filename: string;
  title: string | null;
  category: string;
  durationSeconds: number | null;
  quality: string | null;
  orientation: string | null;
  thumbnailPath: string | null;
  fileSize: number | null;
  viewCount: number;
  upvoteCount: number;
  commentCount: number;
  finishCount: number;
  isLocked: boolean;
  createdAt: string;
}

export default function MediaViewerPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  const [video, setVideo] = useState<Video | null>(null);
  const [relatedVideos, setRelatedVideos] = useState<Video[]>([]);
  const [loading, setLoading] = useState(true);
  const [upvoted, setUpvoted] = useState(false);
  const [upvoting, setUpvoting] = useState(false);
  const [addToPlaylistOpen, setAddToPlaylistOpen] = useState(false);
  const currentTime = 0; // TODO: Track video playback time
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
  const { settings } = useSettingsStore();

  const videoId = parseInt(id || '0', 10);

  // Fetch video details
  useEffect(() => {
    if (video) {
      document.title = `${video.title || video.filename} | Media Gallery`;
    }
  }, [video]);

  useEffect(() => {
    const fetchVideo = async () => {
      try {
        setLoading(true);
        const response = await mediaPublicApi.get(`/public/${videoId}`);
        setVideo(response.data.video);

        // Check if locked and user not authenticated
        if (response.data.video.isLocked) {
          if (!useAuthStore.getState().isAuthenticated) {
            Modal.confirm({
              title: 'Login Required',
              content: 'This video is locked. Please log in to watch.',
              okText: 'Go to Login',
              cancelText: 'Back to Gallery',
              onOk: () => {
                navigate('/login', { state: { from: `/gallery/watch/${videoId}` } });
              },
              onCancel: () => {
                navigate('/gallery');
              },
            });
          }
        }
      } catch (error: unknown) {
        if (axios.isAxiosError(error) && error.response?.status === 404) {
          message.error('Video not found');
          navigate('/gallery');
        } else if (axios.isAxiosError(error) && error.response?.status === 401) {
          Modal.confirm({
            title: 'Login Required',
            content: 'This video is locked. Please log in to watch.',
            okText: 'Go to Login',
            cancelText: 'Back to Gallery',
            onOk: () => {
              navigate('/login', { state: { from: `/gallery/watch/${videoId}` } });
            },
            onCancel: () => {
              navigate('/gallery');
            },
          });
        } else {
          message.error('Failed to load video');
          console.error('Failed to fetch video:', error);
        }
      } finally {
        setLoading(false);
      }
    };

    if (videoId) {
      fetchVideo();
    }
  }, [videoId]);

  // Fetch related videos
  useEffect(() => {
    const fetchRelated = async () => {
      if (!video) return;

      try {
        const response = await mediaPublicApi.get('/public', {
          params: {
            category: video.category,
            limit: 4,
            sort: 'popular',
          },
        });

        // Filter out current video
        const related = response.data.videos.filter((v: Video) => v.id !== videoId);
        setRelatedVideos(related.slice(0, 3));
      } catch (error) {
        console.error('Failed to fetch related videos:', error);
      }
    };

    fetchRelated();
  }, [video, videoId]);

  // Check upvote status
  useEffect(() => {
    const checkUpvoteStatus = async () => {
      try {
        const sessionId = getOrCreateSessionId();
        const response = await mediaPublicApi.get(`/public/${videoId}/upvote-status`, {
          params: { sessionId },
        });
        setUpvoted(response.data.upvoted);
      } catch (error) {
        console.error('Failed to check upvote status:', error);
      }
    };

    if (videoId) {
      checkUpvoteStatus();
    }
  }, [videoId]);

  const handleUpvote = async () => {
    try {
      setUpvoting(true);
      const sessionId = getOrCreateSessionId();

      const response = await mediaPublicApi.post(`/public/${videoId}/upvote`, {
        sessionId,
      });

      setUpvoted(response.data.upvoted);

      // Update local upvote count
      if (video) {
        setVideo({
          ...video,
          upvoteCount: video.upvoteCount + (response.data.upvoted ? 1 : -1),
        });
      }

      message.success(response.data.upvoted ? 'Upvoted!' : 'Upvote removed');
    } catch (error: unknown) {
      if (axios.isAxiosError(error) && error.response?.status === 401) {
        message.warning('Please log in to upvote');
      } else {
        message.error('Failed to upvote');
      }
      console.error('Failed to upvote:', error);
    } finally {
      setUpvoting(false);
    }
  };

  const formatCount = (count: number) => {
    if (count >= 1000000) {
      return `${(count / 1000000).toFixed(1)}M`;
    }
    if (count >= 1000) {
      return `${(count / 1000).toFixed(1)}K`;
    }
    return count.toString();
  };

  if (loading) {
    return (
      <>
        <PublicNavBar activePath="/gallery" />
        <div style={{ textAlign: 'center', padding: 100 }}>
          <Spin size="large" />
        </div>
      </>
    );
  }

  if (!video) {
    return null;
  }

  const title = video.title || video.filename.replace(/\.[^/.]+$/, '');

  return (
    <div>
      <PublicNavBar activePath="/gallery" />
      {/* Back button */}
      <Button
        icon={<ArrowLeftOutlined />}
        onClick={() => navigate('/gallery')}
        style={{ marginBottom: 16, marginLeft: 16, marginTop: 16 }}
      >
        Back to Gallery
      </Button>

      {/* Video player */}
      <div style={{ marginBottom: 24 }}>
        <VideoPlayer
          videoId={videoId}
          autoplay={!video.isLocked}
        />
      </div>

      {/* Video metadata */}
      <div style={{ marginBottom: 32 }}>
        <Title level={3} style={{ marginBottom: 8 }}>
          {title}
        </Title>

        <Space size={24} wrap style={{ marginBottom: 16 }}>
          <Space size={8}>
            <EyeOutlined style={{ fontSize: 16 }} />
            <Text>{formatCount(video.viewCount)} views</Text>
          </Space>

          <Button
            type={upvoted ? 'primary' : 'default'}
            icon={upvoted ? <LikeFilled /> : <LikeOutlined />}
            onClick={handleUpvote}
            loading={upvoting}
            size="large"
            aria-label={upvoted ? 'Remove upvote' : 'Upvote this video'}
          >
            {formatCount(video.upvoteCount)}
          </Button>

          {isAuthenticated && (
            <Button
              icon={<PlusOutlined />}
              size="large"
              onClick={() => setAddToPlaylistOpen(true)}
            >
              Playlist
            </Button>
          )}

          <Tag color="purple" style={{ fontSize: 14, padding: '4px 12px' }}>
            {video.category}
          </Tag>

          {video.quality && (
            <Tag color="blue" style={{ fontSize: 14, padding: '4px 12px' }}>
              {video.quality}
            </Tag>
          )}
        </Space>

        {/* Reaction buttons */}
        <div style={{ marginTop: 16 }}>
          <Text strong style={{ display: 'block', marginBottom: 8 }}>
            React to this video:
          </Text>
          <ReactionButtons videoId={videoId} currentTime={currentTime} />
        </div>
      </div>

      <Divider />

      {/* Related videos */}
      {relatedVideos.length > 0 && (
        <div style={{ marginBottom: 32 }}>
          <Title level={4} style={{ marginBottom: 16 }}>
            Related Videos
          </Title>
          <Row gutter={[16, 16]}>
            {relatedVideos.map((relatedVideo) => (
              <Col key={relatedVideo.id} xs={24} sm={12} md={8}>
                <PublicVideoCard video={relatedVideo} />
              </Col>
            ))}
          </Row>
        </div>
      )}

      {/* Cross-site CTA */}
      {settings?.enableInfluence !== false && (
        <>
          <Divider />
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              padding: '12px 16px',
              background: 'linear-gradient(135deg, rgba(0,90,156,0.15) 0%, rgba(82,196,26,0.1) 100%)',
              borderRadius: 8,
              border: '1px solid rgba(0,90,156,0.25)',
              flexWrap: 'wrap',
              gap: 12,
            }}
          >
            <div>
              <Text strong>Want to take action?</Text>
              <br />
              <Text type="secondary" style={{ fontSize: 13 }}>
                Join an active campaign and make your voice heard.
              </Text>
            </div>
            <Link to="/campaigns">
              <Button type="primary" icon={<SendOutlined />}>
                View Campaigns
              </Button>
            </Link>
          </div>
        </>
      )}

      <Divider />

      {/* Comments section */}
      <div>
        <CommentSection videoId={videoId} />
      </div>

      {/* Add to Playlist Modal */}
      <AddToPlaylistModal
        videoId={videoId}
        open={addToPlaylistOpen}
        onClose={() => setAddToPlaylistOpen(false)}
      />
    </div>
  );
}
