import { Drawer, Select, Button, message } from 'antd';
import { useState } from 'react';
import { mediaApi } from '@/lib/media-api';
import { getErrorMessage } from '@/utils/getErrorMessage';

interface BulkAccessLevelModalProps {
  open: boolean;
  videoIds: number[];
  onClose: () => void;
  onSuccess: () => void;
}

const ACCESS_LEVEL_OPTIONS = [
  { value: 'free', label: 'Free — Anyone can view' },
  { value: 'member', label: 'Member — Any active subscriber' },
  { value: 'premium', label: 'Premium — Premium subscribers only' },
];

export default function BulkAccessLevelModal({ open, videoIds, onClose, onSuccess }: BulkAccessLevelModalProps) {
  const [accessLevel, setAccessLevel] = useState<string>('free');
  const [loading, setLoading] = useState(false);

  const handleOk = async () => {
    setLoading(true);
    try {
      const { data } = await mediaApi.post<{ updatedCount: number }>('/videos/bulk-access-level', {
        videoIds,
        accessLevel,
      });
      message.success(`Updated access level to "${accessLevel}" for ${data.updatedCount} video(s)`);
      onSuccess();
    } catch (error: unknown) {
      message.error(getErrorMessage(error, 'Failed to update access levels'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <Drawer
      title={`Set Access Level (${videoIds.length} video${videoIds.length !== 1 ? 's' : ''})`}
      open={open}
      onClose={onClose}
      width={480}
      placement="right"
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      extra={
        <Button type="primary" onClick={handleOk} loading={loading}>
          Apply
        </Button>
      }
    >
      <div style={{ marginTop: 16 }}>
        <Select
          value={accessLevel}
          onChange={setAccessLevel}
          options={ACCESS_LEVEL_OPTIONS}
          style={{ width: '100%' }}
          size="large"
        />
      </div>
    </Drawer>
  );
}
