import { useState } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  DatePicker,
  TimePicker,
  Select,
  Result,
  Switch,
  Typography,
  message,
} from 'antd';
import { PlusOutlined, CheckCircleOutlined, VideoCameraOutlined, CopyOutlined } from '@ant-design/icons';
import axios from 'axios';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import { getErrorMessage } from '@/utils/getErrorMessage';

const { TextArea } = Input;
const { Text } = Typography;

interface EventSubmissionFormProps {
  /** Pre-fill the date picker with this date (YYYY-MM-DD) */
  initialDate?: string;
  onSuccess?: () => void;
  gancioUrl?: string;
  /** User is authenticated and non-TEMP */
  canCreateMeeting?: boolean;
  /** Site setting: enableMeet */
  meetEnabled?: boolean;
}

export default function EventSubmissionForm({ initialDate, onSuccess, gancioUrl, canCreateMeeting, meetEnabled }: EventSubmissionFormProps) {
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState(false);
  const [addVideo, setAddVideo] = useState(false);
  const [createdMeetingUrl, setCreatedMeetingUrl] = useState<string | null>(null);

  const handleSubmit = async (values: any) => {
    setSubmitting(true);
    try {
      let description = values.description || '';
      let tags: string[] = values.tags || [];

      // Step 1: Create Jitsi meeting if toggle is on
      if (addVideo) {
        const dateStr = values.date.format('YYYY-MM-DD');
        const startISO = dayjs(`${dateStr}T${values.startTime.format('HH:mm')}`).toISOString();
        const endISO = dayjs(`${dateStr}T${values.endTime.format('HH:mm')}`).toISOString();

        const { data: meeting } = await api.post('/jitsi/meetings', {
          title: values.title,
          startTime: startISO,
          endTime: endISO,
        });

        const meetingUrl = `${window.location.origin}/meet/${meeting.slug}`;
        description = description
          ? `${description}\n\n---\nJoin Video Meeting: ${meetingUrl}`
          : `Join Video Meeting: ${meetingUrl}`;
        if (!tags.includes('video-meeting')) {
          tags = [...tags, 'video-meeting'];
        }
        setCreatedMeetingUrl(meetingUrl);
      }

      // Step 2: Submit event to Gancio
      await axios.post('/api/events/submit', {
        title: values.title,
        description: description || undefined,
        date: values.date.format('YYYY-MM-DD'),
        startTime: values.startTime.format('HH:mm'),
        endTime: values.endTime.format('HH:mm'),
        location: values.location || undefined,
        tags: tags.length > 0 ? tags : undefined,
      });
      setSuccess(true);
      form.resetFields();
      onSuccess?.();
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to submit event'));
    } finally {
      setSubmitting(false);
    }
  };

  const handleReset = () => {
    setSuccess(false);
    setAddVideo(false);
    setCreatedMeetingUrl(null);
    form.resetFields();
  };

  if (success) {
    return (
      <Card size="small" style={{ borderLeft: '4px solid #52c41a', marginBottom: 8 }}>
        <Result
          icon={<CheckCircleOutlined style={{ color: '#52c41a', fontSize: 32 }} />}
          title="Event Submitted!"
          subTitle="Your event has been added to the community calendar."
          style={{ padding: '12px 0' }}
          extra={
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'center' }}>
              {createdMeetingUrl && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '4px 8px', background: 'rgba(82,196,26,0.1)', borderRadius: 6 }}>
                  <VideoCameraOutlined style={{ color: '#52c41a' }} />
                  <Text style={{ fontSize: 12, color: 'rgba(255,255,255,0.75)' }} copyable={{ text: createdMeetingUrl, icon: <CopyOutlined style={{ fontSize: 12 }} /> }}>
                    {createdMeetingUrl}
                  </Text>
                </div>
              )}
              {gancioUrl && (
                <Button type="link" size="small" href={gancioUrl} target="_blank" rel="noopener noreferrer">
                  View on Community Calendar
                </Button>
              )}
              <Button size="small" onClick={handleReset}>
                Submit Another
              </Button>
            </div>
          }
        />
      </Card>
    );
  }

  const defaultDate = initialDate ? dayjs(initialDate) : dayjs().add(1, 'day');

  return (
    <Card
      size="small"
      title={
        <span style={{ fontSize: 13 }}>
          <PlusOutlined style={{ marginRight: 6 }} />
          Submit a Community Event
        </span>
      }
      style={{ borderLeft: '4px solid #52c41a', marginBottom: 8 }}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        size="small"
        initialValues={{
          date: defaultDate,
          startTime: dayjs().hour(18).minute(0),
          endTime: dayjs().hour(20).minute(0),
        }}
      >
        <Form.Item
          name="title"
          label="Event Title"
          rules={[{ required: true, message: 'Title is required' }]}
          style={{ marginBottom: 8 }}
        >
          <Input placeholder="Community Town Hall" maxLength={200} />
        </Form.Item>

        <Form.Item name="description" label="Description" style={{ marginBottom: 8 }}>
          <TextArea
            placeholder="Tell people what this event is about..."
            rows={2}
            maxLength={2000}
            showCount
          />
        </Form.Item>

        <Form.Item
          name="date"
          label="Date"
          rules={[{ required: true, message: 'Date is required' }]}
          style={{ marginBottom: 8 }}
        >
          <DatePicker
            style={{ width: '100%' }}
            disabledDate={(d) => d.isBefore(dayjs(), 'day')}
          />
        </Form.Item>

        <div style={{ display: 'flex', gap: 8 }}>
          <Form.Item
            name="startTime"
            label="Start"
            rules={[{ required: true, message: 'Required' }]}
            style={{ flex: 1, marginBottom: 8 }}
          >
            <TimePicker format="HH:mm" minuteStep={5} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="endTime"
            label="End"
            rules={[{ required: true, message: 'Required' }]}
            style={{ flex: 1, marginBottom: 8 }}
          >
            <TimePicker format="HH:mm" minuteStep={5} style={{ width: '100%' }} />
          </Form.Item>
        </div>

        <Form.Item name="location" label="Location" style={{ marginBottom: 8 }}>
          <Input placeholder="City Hall, 1 Sir Winston Churchill Square" maxLength={500} />
        </Form.Item>

        <Form.Item name="tags" label="Tags" style={{ marginBottom: 12 }}>
          <Select
            mode="tags"
            placeholder="Add tags (e.g. meeting, workshop)"
            maxCount={10}
            style={{ width: '100%' }}
          />
        </Form.Item>

        {canCreateMeeting && meetEnabled && (
          <Form.Item style={{ marginBottom: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Switch checked={addVideo} onChange={setAddVideo} size="small" />
              <Text type="secondary" style={{ fontSize: 13 }}>
                <VideoCameraOutlined style={{ marginRight: 4 }} />
                Add Video Meeting
              </Text>
            </div>
          </Form.Item>
        )}

        <div style={{ textAlign: 'right' }}>
          <Button type="primary" htmlType="submit" loading={submitting} icon={<PlusOutlined />}>
            Submit Event
          </Button>
        </div>
      </Form>
    </Card>
  );
}
