import { Button, Dropdown, message, Modal } from 'antd';
import { useEffect } from 'react';
import {
  EditOutlined,
  PlayCircleOutlined,
  BarChartOutlined,
  CopyOutlined,
  DownloadOutlined,
  PictureOutlined,
  ReloadOutlined,
  DeleteOutlined,
  MoreOutlined,
  LinkOutlined,
  ClockCircleOutlined,
  OrderedListOutlined,
} from '@ant-design/icons';
import { useState } from 'react';
import type { Video } from '@/types/media';
import { mediaApi } from '@/lib/media-api';

interface VideoActionsProps {
  video: Video;
  onEdit?: (video: Video) => void;
  onPreview?: (video: Video) => void;
  onAnalytics?: (video: Video) => void;
  onSchedule?: (video: Video) => void;
  onDelete?: (video: Video) => void;
  onAddToPlaylist?: (video: Video) => void;
  onRefresh?: () => void;
}

export default function VideoActions({
  video,
  onEdit,
  onPreview,
  onAnalytics,
  onSchedule,
  onDelete,
  onAddToPlaylist,
  onRefresh,
}: VideoActionsProps) {
  const [loading, setLoading] = useState(false);

  // Keyboard shortcuts
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Don't trigger if user is typing in an input
      if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
        return;
      }

      switch (e.key.toLowerCase()) {
        case 'e':
          if (!e.ctrlKey && !e.metaKey) {
            e.preventDefault();
            onEdit?.(video);
          }
          break;
        case 'p':
          if (!e.ctrlKey && !e.metaKey) {
            e.preventDefault();
            onPreview?.(video);
          }
          break;
        case 'a':
          if (!e.ctrlKey && !e.metaKey) {
            e.preventDefault();
            onAnalytics?.(video);
          }
          break;
        case 's':
          if (!e.ctrlKey && !e.metaKey) {
            e.preventDefault();
            onSchedule?.(video);
          }
          break;
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [video, onEdit, onPreview, onAnalytics, onSchedule]);

  const handleDuplicate = async () => {
    try {
      setLoading(true);
      await mediaApi.post(`/videos/${video.id}/duplicate`);
      message.success('Video duplicated successfully');
      onRefresh?.();
    } catch (error) {
      message.error('Failed to duplicate video');
    } finally {
      setLoading(false);
    }
  };

  const handleGeneratePreviewLink = async () => {
    try {
      setLoading(true);
      const response = await mediaApi.get(`/videos/${video.id}/preview-link`);
      const { previewUrl, expiryHours } = response.data;

      // Copy to clipboard
      await navigator.clipboard.writeText(previewUrl);

      Modal.success({
        title: 'Preview Link Generated',
        content: (
          <div>
            <p>Preview link copied to clipboard!</p>
            <p style={{ fontSize: 12, color: '#666' }}>Expires in {expiryHours} hours</p>
            <div
              style={{
                marginTop: 12,
                padding: 8,
                background: '#f5f5f5',
                borderRadius: 4,
                wordBreak: 'break-all',
                fontSize: 12,
              }}
            >
              {previewUrl}
            </div>
          </div>
        ),
      });
    } catch (error) {
      message.error('Failed to generate preview link');
    } finally {
      setLoading(false);
    }
  };

  const handleResetAnalytics = () => {
    Modal.confirm({
      title: 'Reset Analytics?',
      content: 'This will permanently delete all view data, watch time, and analytics for this video. This action cannot be undone.',
      okText: 'Reset',
      okType: 'danger',
      onOk: async () => {
        try {
          setLoading(true);
          await mediaApi.post(`/videos/${video.id}/reset-analytics`);
          message.success('Analytics reset successfully');
          onRefresh?.();
        } catch (error) {
          message.error('Failed to reset analytics');
        } finally {
          setLoading(false);
        }
      },
    });
  };

  const handleDownload = () => {
    // TODO: Implement download functionality
    message.info('Download functionality coming soon');
  };

  const handleGenerateThumbnail = () => {
    // TODO: Implement thumbnail generation
    message.info('Thumbnail generation coming soon');
  };

  // Overflow menu items
  const menuItems = [
    {
      key: 'add-to-playlist',
      label: 'Add to Playlist',
      icon: <OrderedListOutlined />,
      onClick: () => onAddToPlaylist?.(video),
    },
    {
      key: 'duplicate',
      label: 'Duplicate',
      icon: <CopyOutlined />,
      onClick: handleDuplicate,
    },
    {
      key: 'preview-link',
      label: 'Generate Preview Link',
      icon: <LinkOutlined />,
      onClick: handleGeneratePreviewLink,
    },
    {
      key: 'divider-1',
      type: 'divider' as const,
    },
    {
      key: 'download',
      label: 'Download',
      icon: <DownloadOutlined />,
      onClick: handleDownload,
    },
    {
      key: 'thumbnail',
      label: 'Generate Thumbnail',
      icon: <PictureOutlined />,
      onClick: handleGenerateThumbnail,
    },
    {
      key: 'divider-2',
      type: 'divider' as const,
    },
    {
      key: 'reset-analytics',
      label: 'Reset Analytics',
      icon: <ReloadOutlined />,
      onClick: handleResetAnalytics,
      danger: true,
    },
    {
      key: 'delete',
      label: 'Delete',
      icon: <DeleteOutlined />,
      onClick: () => onDelete?.(video),
      danger: true,
    },
  ];

  return (
    <div
      style={{
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0,
        background: 'linear-gradient(to top, rgba(0, 0, 0, 0.85), transparent)',
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        gap: 8,
        padding: '8px 12px',
        transition: 'opacity 0.2s ease',
        zIndex: 10,
      }}
      onClick={(e) => e.stopPropagation()}
      role="toolbar"
      aria-label="Video actions"
    >
      {/* Primary actions */}
      <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
        <Button
          type="text"
          size="small"
          icon={<EditOutlined />}
          onClick={(e) => {
            e.stopPropagation();
            onEdit?.(video);
          }}
          title="Edit (E)"
          aria-label="Edit video"
          style={{ color: '#fff' }}
        />
        <Button
          type="text"
          size="small"
          icon={<PlayCircleOutlined />}
          onClick={(e) => {
            e.stopPropagation();
            onPreview?.(video);
          }}
          title="Preview (P)"
          aria-label="Preview video"
          style={{ color: '#fff' }}
        />
        <Button
          type="text"
          size="small"
          icon={<BarChartOutlined />}
          onClick={(e) => {
            e.stopPropagation();
            onAnalytics?.(video);
          }}
          title="Analytics (A)"
          aria-label="View analytics"
          style={{ color: '#fff' }}
        />
        <Button
          type="text"
          size="small"
          icon={<ClockCircleOutlined />}
          onClick={(e) => {
            e.stopPropagation();
            onSchedule?.(video);
          }}
          title="Schedule (S)"
          aria-label="Schedule publishing"
          style={{ color: '#fff' }}
        />
      </div>

      {/* Right side: View count + Overflow menu */}
      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        {/* View count badge */}
        {video.viewCount !== undefined && video.viewCount > 0 && (
          <div
            style={{
              background: 'rgba(0, 0, 0, 0.6)',
              color: '#fff',
              padding: '2px 8px',
              borderRadius: 4,
              fontSize: 11,
              display: 'flex',
              alignItems: 'center',
              gap: 4,
            }}
          >
            <BarChartOutlined style={{ fontSize: 11 }} />
            {video.viewCount.toLocaleString()}
          </div>
        )}

        {/* Overflow menu */}
        <Dropdown
          menu={{ items: menuItems }}
          trigger={['click']}
          placement="topRight"
        >
          <Button
            type="text"
            size="small"
            icon={<MoreOutlined />}
            onClick={(e) => e.stopPropagation()}
            loading={loading}
            aria-label="More actions menu"
            style={{ color: '#fff' }}
          />
        </Dropdown>
      </div>
    </div>
  );
}
