import { useState, useEffect } from 'react';
import { Drawer, Checkbox, Button, Input, Space, Typography, Spin, Divider, message, theme } from 'antd';
import { PlusOutlined, UnorderedListOutlined } from '@ant-design/icons';
import { mediaApi } from '@/lib/media-api';
import { mediaPublicApi } from '@/lib/media-public-api';
import type { PlaylistSummary } from '@/types/media';
import axios from 'axios';

const { Text } = Typography;

interface AddToPlaylistModalProps {
  videoId: number;
  open: boolean;
  onClose: () => void;
}

interface PlaylistWithSelected extends PlaylistSummary {
  hasVideo: boolean;
}

export default function AddToPlaylistModal({
  videoId,
  open,
  onClose,
}: AddToPlaylistModalProps) {
  const { token } = theme.useToken();
  const [playlists, setPlaylists] = useState<PlaylistWithSelected[]>([]);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [selections, setSelections] = useState<Record<number, boolean>>({});

  // Inline create state
  const [showCreate, setShowCreate] = useState(false);
  const [newName, setNewName] = useState('');
  const [creating, setCreating] = useState(false);

  // Fetch user's playlists and check which ones contain the video
  useEffect(() => {
    if (!open) return;

    const fetchPlaylists = async () => {
      try {
        setLoading(true);
        const { data } = await mediaApi.get('/playlists/my');
        const userPlaylists: PlaylistSummary[] = data.data || [];

        // For each playlist, check if it contains the video
        const withSelection = await Promise.all(
          userPlaylists.map(async (p) => {
            try {
              const { data: detail } = await mediaPublicApi.get(
                `/playlists/${p.id}`
              );
              const hasVideo = (detail.videos || []).some(
                (v: any) => v.mediaId === videoId
              );
              return { ...p, hasVideo };
            } catch {
              return { ...p, hasVideo: false };
            }
          })
        );

        setPlaylists(withSelection);
        // Initialize selections from current state
        const initial: Record<number, boolean> = {};
        withSelection.forEach((p) => {
          initial[p.id] = p.hasVideo;
        });
        setSelections(initial);
      } catch {
        message.error('Failed to load playlists');
      } finally {
        setLoading(false);
      }
    };

    fetchPlaylists();
  }, [open, videoId]);

  const handleToggle = (playlistId: number, checked: boolean) => {
    setSelections((prev) => ({ ...prev, [playlistId]: checked }));
  };

  const handleSave = async () => {
    try {
      setSaving(true);

      const promises: Promise<any>[] = [];

      for (const playlist of playlists) {
        const wasInPlaylist = playlist.hasVideo;
        const shouldBeInPlaylist = selections[playlist.id];

        if (shouldBeInPlaylist && !wasInPlaylist) {
          // Add to playlist
          promises.push(
            mediaApi.post(`/playlists/${playlist.id}/videos`, {
              mediaId: videoId,
            })
          );
        } else if (!shouldBeInPlaylist && wasInPlaylist) {
          // Remove from playlist
          promises.push(
            mediaApi.delete(`/playlists/${playlist.id}/videos/${videoId}`)
          );
        }
      }

      await Promise.all(promises);
      message.success('Playlists updated');
      onClose();
    } catch {
      message.error('Failed to update playlists');
    } finally {
      setSaving(false);
    }
  };

  const handleCreateNew = async () => {
    if (!newName.trim()) return;

    try {
      setCreating(true);
      const { data } = await mediaApi.post('/playlists/', {
        name: newName.trim(),
        isPublic: false,
      });

      // Add video to the new playlist
      await mediaApi.post(`/playlists/${data.id}/videos`, { mediaId: videoId });

      message.success(`Created "${data.name}" and added video`);
      setNewName('');
      setShowCreate(false);

      // Refresh the list
      setPlaylists((prev) => [
        ...prev,
        { ...data, hasVideo: true, isOwner: true, creator: { id: '', name: '', email: '' }, videoCount: 1, totalDurationSeconds: 0, viewCount: 0, thumbnailUrl: null, isFeatured: false, featuredPosition: null },
      ]);
      setSelections((prev) => ({ ...prev, [data.id]: true }));
    } catch (error: unknown) {
      if (axios.isAxiosError(error) && error.response?.status === 409) {
        message.error('You already have a playlist with this name');
      } else {
        message.error('Failed to create playlist');
      }
    } finally {
      setCreating(false);
    }
  };

  return (
    <Drawer
      title="Add to Playlist"
      open={open}
      onClose={onClose}
      width={480}
      placement="right"
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      extra={
        <Button type="primary" onClick={handleSave} loading={saving}>
          Save
        </Button>
      }
    >
      {loading ? (
        <div style={{ textAlign: 'center', padding: 32 }}>
          <Spin />
        </div>
      ) : (
        <>
          {playlists.length === 0 && !showCreate ? (
            <div style={{ textAlign: 'center', padding: 24 }}>
              <UnorderedListOutlined
                style={{ fontSize: 36, color: token.colorTextSecondary, marginBottom: 12 }}
              />
              <Text
                type="secondary"
                style={{ display: 'block', marginBottom: 16 }}
              >
                You don't have any playlists yet
              </Text>
            </div>
          ) : (
            <div style={{ maxHeight: 300, overflowY: 'auto' }}>
              {playlists.map((p) => (
                <div
                  key={p.id}
                  style={{
                    padding: '8px 0',
                    borderBottom: '1px solid rgba(255,255,255,0.04)',
                  }}
                >
                  <Checkbox
                    checked={selections[p.id] ?? false}
                    onChange={(e) => handleToggle(p.id, e.target.checked)}
                  >
                    <Space>
                      <Text>{p.name}</Text>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        ({p.videoCount} videos)
                      </Text>
                    </Space>
                  </Checkbox>
                </div>
              ))}
            </div>
          )}

          <Divider style={{ margin: '12px 0' }} />

          {showCreate ? (
            <Space.Compact style={{ width: '100%' }}>
              <Input
                placeholder="New playlist name"
                value={newName}
                onChange={(e) => setNewName(e.target.value)}
                onPressEnter={handleCreateNew}
                maxLength={100}
                autoFocus
              />
              <Button
                type="primary"
                onClick={handleCreateNew}
                loading={creating}
                disabled={!newName.trim()}
              >
                Create
              </Button>
              <Button onClick={() => setShowCreate(false)}>Cancel</Button>
            </Space.Compact>
          ) : (
            <Button
              type="dashed"
              icon={<PlusOutlined />}
              onClick={() => setShowCreate(true)}
              block
            >
              Create New Playlist
            </Button>
          )}
        </>
      )}
    </Drawer>
  );
}
