import { useState } from 'react';
import { Drawer, Form, Input, Switch, Button, message } from 'antd';
import { mediaApi } from '@/lib/media-api';
import axios from 'axios';

interface CreatePlaylistModalProps {
  open: boolean;
  onClose: () => void;
  onCreated?: (playlist: any) => void;
}

export default function CreatePlaylistModal({
  open,
  onClose,
  onCreated,
}: CreatePlaylistModalProps) {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

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

      const { data } = await mediaApi.post('/playlists/', {
        name: values.name,
        description: values.description || undefined,
        isPublic: values.isPublic ?? false,
      });

      message.success('Playlist created');
      form.resetFields();
      onCreated?.(data);
      onClose();
    } catch (error: unknown) {
      if (axios.isAxiosError(error) && error.response?.status === 409) {
        message.error('You already have a playlist with this name');
      } else if (!(error instanceof Object && 'errorFields' in error)) {
        message.error('Failed to create playlist');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Drawer
      title="Create Playlist"
      open={open}
      onClose={() => {
        form.resetFields();
        onClose();
      }}
      placement="right"
      width={420}
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      extra={
        <Button type="primary" onClick={handleSubmit} loading={loading}>
          Create
        </Button>
      }
    >
      <Form form={form} layout="vertical">
        <Form.Item
          name="name"
          label="Name"
          rules={[
            { required: true, message: 'Please enter a playlist name' },
            { max: 100, message: 'Name must be 100 characters or less' },
          ]}
        >
          <Input placeholder="My Playlist" maxLength={100} />
        </Form.Item>

        <Form.Item name="description" label="Description">
          <Input.TextArea
            placeholder="Optional description..."
            rows={3}
            maxLength={500}
          />
        </Form.Item>

        <Form.Item
          name="isPublic"
          label="Public"
          valuePropName="checked"
          initialValue={false}
        >
          <Switch checkedChildren="Public" unCheckedChildren="Private" />
        </Form.Item>
      </Form>
    </Drawer>
  );
}
