import { useState } from 'react';
import {
  Modal,
  Form,
  Input,
  Button,
  Result,
  message,
  Grid,
  Typography,
} from 'antd';
import {
  ScheduleOutlined,
  ClockCircleOutlined,
  EnvironmentOutlined,
  CheckCircleOutlined,
  VideoCameraOutlined,
} from '@ant-design/icons';
import { Link } from 'react-router-dom';
import axios from 'axios';
import dayjs from 'dayjs';
import { getErrorMessage } from '@/utils/getErrorMessage';

const { Text } = Typography;

interface ShiftData {
  id: string;
  title: string;
  date: string;
  startTime: string;
  endTime: string;
  location: string | null;
  meeting?: { id: string; slug: string; isActive: boolean } | null;
}

interface ShiftSignupModalProps {
  shift: ShiftData | null;
  open: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

export default function ShiftSignupModal({ shift, open, onClose, onSuccess }: ShiftSignupModalProps) {
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);
  const [successShift, setSuccessShift] = useState<ShiftData | null>(null);

  const handleSignup = async (values: { name: string; email: string; phone?: string }) => {
    if (!shift) return;
    setSubmitting(true);
    try {
      await axios.post(`/api/map/shifts/public/${shift.id}/signup`, {
        name: values.name,
        email: values.email,
        phone: values.phone || undefined,
      });
      setSuccessShift(shift);
      onClose();
      form.resetFields();
      onSuccess?.();
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to sign up'));
    } finally {
      setSubmitting(false);
    }
  };

  const handleClose = () => {
    form.resetFields();
    onClose();
  };

  return (
    <>
      {/* Signup Form Modal */}
      <Modal
        title={
          <span>
            <ScheduleOutlined style={{ marginRight: 8 }} />
            Sign Up — {shift?.title}
          </span>
        }
        open={open}
        onCancel={handleClose}
        footer={null}
        width={isMobile ? '100%' : 440}
        style={{ maxWidth: '95vw' }}
        destroyOnClose
      >
        {shift && (
          <div style={{
            padding: '12px 16px',
            background: 'rgba(255,255,255,0.04)',
            borderRadius: 8,
            marginBottom: 16,
          }}>
            <div>
              <ScheduleOutlined style={{ marginRight: 8 }} />
              <Text>{dayjs(shift.date).format('dddd, MMMM D, YYYY')}</Text>
            </div>
            <div>
              <ClockCircleOutlined style={{ marginRight: 8 }} />
              <Text>{shift.startTime} — {shift.endTime}</Text>
            </div>
            {shift.location && (
              <div>
                <EnvironmentOutlined style={{ marginRight: 8 }} />
                <Text>{shift.location}</Text>
              </div>
            )}
          </div>
        )}

        <Form form={form} layout="vertical" onFinish={handleSignup}>
          <Form.Item
            name="name"
            label="Your Name"
            rules={[{ required: true, message: 'Name is required' }]}
          >
            <Input placeholder="Jane Doe" autoFocus />
          </Form.Item>
          <Form.Item
            name="email"
            label="Email Address"
            rules={[
              { required: true, message: 'Email is required' },
              { type: 'email', message: 'Enter a valid email' },
            ]}
          >
            <Input placeholder="jane@example.com" />
          </Form.Item>
          <Form.Item name="phone" label="Phone (optional)">
            <Input placeholder="555-123-4567" />
          </Form.Item>
          <div style={{ textAlign: 'right' }}>
            <Button onClick={handleClose} style={{ marginRight: 8 }}>
              Cancel
            </Button>
            <Button type="primary" htmlType="submit" loading={submitting}>
              Sign Up
            </Button>
          </div>
        </Form>
      </Modal>

      {/* Success Modal */}
      <Modal
        open={!!successShift}
        onCancel={() => setSuccessShift(null)}
        footer={
          <Button type="primary" onClick={() => setSuccessShift(null)}>
            Done
          </Button>
        }
        width={isMobile ? '100%' : 440}
        style={{ maxWidth: '95vw' }}
      >
        {successShift && (
          <Result
            icon={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
            title="You're signed up!"
            subTitle="A confirmation email has been sent with your shift details."
            extra={
              <div style={{
                textAlign: 'left',
                padding: '16px',
                background: 'rgba(255,255,255,0.04)',
                borderRadius: 8,
              }}>
                <div style={{ marginBottom: 4 }}>
                  <Text strong>{successShift.title}</Text>
                </div>
                <div style={{ marginBottom: 4 }}>
                  <ScheduleOutlined style={{ marginRight: 8 }} />
                  <Text>{dayjs(successShift.date).format('dddd, MMMM D, YYYY')}</Text>
                </div>
                <div style={{ marginBottom: 4 }}>
                  <ClockCircleOutlined style={{ marginRight: 8 }} />
                  <Text>{successShift.startTime} — {successShift.endTime}</Text>
                </div>
                {successShift.location && (
                  <div>
                    <EnvironmentOutlined style={{ marginRight: 8 }} />
                    <Text>{successShift.location}</Text>
                  </div>
                )}
                {successShift.meeting?.isActive && (
                  <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid rgba(255,255,255,0.08)' }}>
                    <Button
                      type="primary"
                      ghost
                      block
                      icon={<VideoCameraOutlined />}
                      href={`/meet/${successShift.meeting.slug}`}
                      target="_blank"
                    >
                      Join Video Briefing
                    </Button>
                  </div>
                )}
                <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid rgba(255,255,255,0.08)' }}>
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    <Link to="/login" style={{ color: 'inherit', textDecoration: 'underline' }}>Create an account</Link> to access GPS-guided canvassing and track your volunteer activity.
                  </Text>
                </div>
              </div>
            }
          />
        )}
      </Modal>
    </>
  );
}
