import { Drawer, Form, Input, Select, Switch, Button, Space, message, Spin } from 'antd';
import { EditOutlined } from '@ant-design/icons';
import { useState, useEffect } from 'react';
import { mediaApi } from '@/lib/media-api';
import type { Video } from '@/types/media';
import axios from 'axios';

interface EditVideoDrawerProps {
  video: Video | null;
  open: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

const CATEGORY_OPTIONS = [
  { value: 'videos', label: 'Videos' },
  { value: 'curated', label: 'Curated' },
  { value: 'compilations', label: 'Compilations' },
  { value: 'playback', label: 'Playback' },
  { value: 'highlights', label: 'Highlights' },
];

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 EditVideoModal({ video, open, onClose, onSuccess }: EditVideoDrawerProps) {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [fetching, setFetching] = useState(false);

  // Fetch full video details when drawer opens (list query omits some fields)
  useEffect(() => {
    if (open && video) {
      setFetching(true);
      mediaApi
        .get<{ video: Video }>(`/videos/${video.id}`)
        .then(({ data }) => {
          const v = data.video;
          form.setFieldsValue({
            title: v.title || '',
            producer: v.producer || '',
            creator: v.creator || '',
            category: v.category || undefined,
            tags: Array.isArray(v.tags) ? v.tags : [],
            quality: v.quality || '',
            isShort: v.isShort ?? false,
            accessLevel: v.accessLevel || 'free',
          });
        })
        .catch(() => {
          // Fallback to data we already have from the list
          form.setFieldsValue({
            title: video.title || '',
            producer: video.producer || '',
            creator: video.creator || '',
            category: video.category || undefined,
            tags: Array.isArray(video.tags) ? video.tags : [],
            quality: video.quality || '',
            isShort: video.isShort ?? false,
            accessLevel: video.accessLevel || 'free',
          });
        })
        .finally(() => setFetching(false));
    }
  }, [open, video, form]);

  const handleSave = async () => {
    if (!video) return;

    try {
      const values = await form.validateFields();
      setLoading(true);

      const payload: Record<string, unknown> = {};
      if (values.title) payload.title = values.title;
      // Allow clearing optional fields by sending null
      payload.producer = values.producer || null;
      payload.creator = values.creator || null;
      payload.category = values.category || null;
      payload.tags = values.tags && values.tags.length > 0 ? values.tags : null;
      if (values.isShort !== undefined) payload.isShort = values.isShort;
      if (values.accessLevel) payload.accessLevel = values.accessLevel;

      await mediaApi.patch(`/videos/${video.id}`, payload);
      message.success('Video updated successfully');
      onSuccess?.();
      onClose();
    } catch (error: unknown) {
      if (axios.isAxiosError(error) && error.response?.data?.message) {
        message.error(error.response.data.message);
      }
      // form validation errors are shown inline
    } finally {
      setLoading(false);
    }
  };

  return (
    <Drawer
      title={
        <span>
          <EditOutlined style={{ marginRight: 8 }} />
          Edit Video
        </span>
      }
      open={open}
      onClose={onClose}
      width={480}
      destroyOnClose
      extra={
        <Space>
          <Button onClick={onClose}>Cancel</Button>
          <Button type="primary" onClick={handleSave} loading={loading}>
            Save
          </Button>
        </Space>
      }
    >
      {fetching ? (
        <div style={{ textAlign: 'center', padding: 48 }}>
          <Spin size="large" />
        </div>
      ) : (
        <Form form={form} layout="vertical">
          <Form.Item
            name="title"
            label="Title"
            rules={[{ required: true, message: 'Title is required' }]}
          >
            <Input placeholder="Video title" maxLength={500} />
          </Form.Item>

          <Form.Item name="producer" label="Producer">
            <Input placeholder="Producer name" maxLength={200} />
          </Form.Item>

          <Form.Item name="creator" label="Creator">
            <Input placeholder="Creator name" maxLength={200} />
          </Form.Item>

          <Form.Item name="category" label="Category">
            <Select
              placeholder="Select category"
              options={CATEGORY_OPTIONS}
              allowClear
            />
          </Form.Item>

          <Form.Item name="accessLevel" label="Access Level">
            <Select options={ACCESS_LEVEL_OPTIONS} />
          </Form.Item>

          <Form.Item name="isShort" label="Short Video" valuePropName="checked">
            <Switch checkedChildren="Yes" unCheckedChildren="No" />
          </Form.Item>

          <Form.Item name="tags" label="Tags">
            <Select
              mode="tags"
              placeholder="Type to add tags"
              tokenSeparators={[',']}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item name="quality" label="Quality">
            <Input disabled placeholder="Auto-detected" />
          </Form.Item>
        </Form>
      )}
    </Drawer>
  );
}
