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

interface CreateAlbumModalProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
  selectedPhotoIds?: number[];
}

export default function CreateAlbumModal({
  open,
  onClose,
  onSuccess,
  selectedPhotoIds = [],
}: CreateAlbumModalProps) {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const handleCreate = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      await mediaApi.post('/albums', {
        title: values.title,
        description: values.description,
        photoIds: selectedPhotoIds.length > 0 ? selectedPhotoIds : undefined,
      });
      message.success('Album created');
      form.resetFields();
      onSuccess();
    } catch (error: unknown) {
      if (axios.isAxiosError(error) && error.response?.data?.message) {
        message.error(error.response.data.message);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Drawer
      title="Create Album"
      open={open}
      onClose={onClose}
      width={480}
      placement="right"
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      extra={
        <Button type="primary" onClick={handleCreate} loading={loading}>
          Create
        </Button>
      }
    >
      <Form form={form} layout="vertical">
        <Form.Item name="title" label="Title" rules={[{ required: true, message: 'Title is required' }]}>
          <Input placeholder="Album title" />
        </Form.Item>
        <Form.Item name="description" label="Description">
          <Input.TextArea rows={3} placeholder="Optional description" />
        </Form.Item>
      </Form>
      {selectedPhotoIds.length > 0 && (
        <div style={{ color: '#999', fontSize: 12 }}>
          {selectedPhotoIds.length} photo{selectedPhotoIds.length > 1 ? 's' : ''} will be added to this album
        </div>
      )}
    </Drawer>
  );
}
