import { useState, useEffect, useCallback } from 'react';
import { Drawer, Input, Select, Typography, message, Space, Button } from 'antd';
import { VideoCameraOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import { mediaApi } from '@/lib/media-api';
import type { FriendListItem } from '@/types/social';
import { getErrorMessage } from '@/utils/getErrorMessage';

interface RecommendVideoModalProps {
  open: boolean;
  onClose: () => void;
  /** Pre-selected video ID (when recommending from media viewer) */
  preselectedVideoId?: number;
  /** Pre-selected friend ID (when recommending from profile) */
  preselectedFriendId?: string;
}

interface VideoOption {
  id: number;
  title: string | null;
  filename: string;
}

export default function RecommendVideoModal({
  open,
  onClose,
  preselectedVideoId,
  preselectedFriendId,
}: RecommendVideoModalProps) {
  const [friends, setFriends] = useState<FriendListItem[]>([]);
  const [videos, setVideos] = useState<VideoOption[]>([]);
  const [selectedFriendId, setSelectedFriendId] = useState<string | undefined>(preselectedFriendId);
  const [selectedVideoId, setSelectedVideoId] = useState<number | undefined>(preselectedVideoId);
  const [messageText, setMessageText] = useState('');
  const [sending, setSending] = useState(false);
  const [loadingFriends, setLoadingFriends] = useState(false);
  const [loadingVideos, setLoadingVideos] = useState(false);

  useEffect(() => {
    if (open) {
      loadFriends();
      loadVideos('');
      setSelectedFriendId(preselectedFriendId);
      setSelectedVideoId(preselectedVideoId);
      setMessageText('');
    }
  }, [open, preselectedFriendId, preselectedVideoId]);

  const loadFriends = async () => {
    setLoadingFriends(true);
    try {
      const { data } = await api.get('/social/friends', { params: { limit: 100 } });
      setFriends(data.friends || []);
    } catch {} finally {
      setLoadingFriends(false);
    }
  };

  const loadVideos = useCallback(async (search: string) => {
    setLoadingVideos(true);
    try {
      const { data } = await mediaApi.get('/videos', {
        params: { search: search || undefined, limit: 50, shared: true },
      });
      setVideos(
        (data.videos || data.data || []).map((v: any) => ({
          id: v.id,
          title: v.title,
          filename: v.filename,
        })),
      );
    } catch {
      // Fallback: if media API not available, clear list
      setVideos([]);
    } finally {
      setLoadingVideos(false);
    }
  }, []);

  const handleSend = async () => {
    if (!selectedFriendId || !selectedVideoId) {
      message.warning('Please select a friend and a video');
      return;
    }

    setSending(true);
    try {
      await api.post('/social/recommendations', {
        userId: selectedFriendId,
        mediaId: selectedVideoId,
        message: messageText.trim() || undefined,
      });
      message.success('Recommendation sent!');
      onClose();
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to send recommendation'));
    } finally {
      setSending(false);
    }
  };

  return (
    <Drawer
      title="Recommend a Video"
      open={open}
      onClose={onClose}
      width={480}
      placement="right"
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      extra={
        <Button type="primary" onClick={handleSend} loading={sending} disabled={!selectedFriendId || !selectedVideoId}>
          Send
        </Button>
      }
    >
      <Space direction="vertical" style={{ width: '100%' }} size="middle">
        <div>
          <Typography.Text strong style={{ display: 'block', marginBottom: 4 }}>
            Send to
          </Typography.Text>
          <Select
            showSearch
            placeholder="Select a friend"
            value={selectedFriendId}
            onChange={setSelectedFriendId}
            loading={loadingFriends}
            style={{ width: '100%' }}
            optionFilterProp="label"
            options={friends.map((f) => ({
              value: f.user.id,
              label: f.user.name || f.user.email,
            }))}
          />
        </div>

        <div>
          <Typography.Text strong style={{ display: 'block', marginBottom: 4 }}>
            Video
          </Typography.Text>
          <Select
            showSearch
            placeholder="Search for a video..."
            value={selectedVideoId}
            onChange={setSelectedVideoId}
            loading={loadingVideos}
            style={{ width: '100%' }}
            filterOption={false}
            onSearch={loadVideos}
            suffixIcon={<VideoCameraOutlined />}
            options={videos.map((v) => ({
              value: v.id,
              label: v.title || v.filename,
            }))}
            notFoundContent={loadingVideos ? 'Searching...' : 'No videos found'}
          />
        </div>

        <div>
          <Typography.Text strong style={{ display: 'block', marginBottom: 4 }}>
            Message (optional)
          </Typography.Text>
          <Input.TextArea
            placeholder="Why you're recommending this..."
            value={messageText}
            onChange={(e) => setMessageText(e.target.value)}
            maxLength={500}
            rows={3}
            showCount
          />
        </div>
      </Space>
    </Drawer>
  );
}
