import { useState } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import {
  ConfigProvider, App, theme, Typography, Form, Input, Button, Card, Result, Grid,
} from 'antd';
import { MailOutlined, UserOutlined, PhoneOutlined, TeamOutlined, HomeOutlined } from '@ant-design/icons';
import axios from 'axios';
import { useAuthStore } from '@/stores/auth.store';
import { useSettingsStore } from '@/stores/settings.store';

const { Title, Text } = Typography;

export default function QuickJoinPage() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { setAccessToken, fetchMe } = useAuthStore();
  const { settings } = useSettingsStore();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  const token = searchParams.get('token');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (values: { email: string; name?: string; phone?: string }) => {
    if (!token) return;
    setLoading(true);
    setError(null);

    try {
      const { data } = await axios.post('/api/volunteer-invite/redeem', {
        token,
        email: values.email,
        name: values.name || undefined,
        phone: values.phone || undefined,
      });

      // Store access token and fetch user profile (refresh token set as httpOnly cookie by server)
      setAccessToken(data.accessToken);
      await fetchMe();

      // Redirect to volunteer map with cut/shift context
      const params = new URLSearchParams();
      if (data.cutId) params.set('cutId', data.cutId);
      if (data.shiftId) params.set('shiftId', data.shiftId);
      const query = params.toString();
      navigate(`/volunteer${query ? `?${query}` : ''}`, { replace: true });
    } catch (err: unknown) {
      const resp = (err as { response?: { data?: { error?: { message?: string; code?: string } } } })
        ?.response?.data?.error;
      if (resp?.code === 'QUICK_JOIN_RATE_LIMIT_EXCEEDED') {
        setError('Too many attempts. Please try again later.');
      } else if (resp?.code === 'INVALID_INVITE_TOKEN' || resp?.code === 'INVALID_TOKEN_TYPE') {
        setError('This invite link has expired or is invalid. Please ask for a new one.');
      } else if (resp?.code === 'ACCOUNT_INACTIVE') {
        setError(resp.message || 'Your account is not active.');
      } else {
        setError(resp?.message || 'Something went wrong. Please try again.');
      }
    } finally {
      setLoading(false);
    }
  };

  // Missing or empty token
  if (!token) {
    return (
      <ConfigProvider
        theme={{
          algorithm: theme.darkAlgorithm,
          token: {
            colorPrimary: settings?.publicColorPrimary ?? '#3498db',
            colorBgBase: settings?.publicColorBgBase ?? '#0d1b2a',
            colorBgContainer: settings?.publicColorBgContainer ?? '#1b2838',
            borderRadius: 8,
          },
        }}
      >
        <App>
          <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
            <Result
              status="warning"
              title="Invalid Invite Link"
              subTitle="This link is missing the invite token. Please scan the QR code again or ask the organizer for a new link."
              extra={
                <Button
                  type="primary"
                  icon={<HomeOutlined />}
                  onClick={() => window.location.href = '/campaigns'}
                >
                  Return to Site
                </Button>
              }
            />
          </div>
        </App>
      </ConfigProvider>
    );
  }

  return (
    <ConfigProvider
      theme={{
        algorithm: theme.darkAlgorithm,
        token: {
          colorPrimary: settings?.publicColorPrimary ?? '#3498db',
          colorBgBase: settings?.publicColorBgBase ?? '#0d1b2a',
          colorBgContainer: settings?.publicColorBgContainer ?? '#1b2838',
          borderRadius: 8,
        },
      }}
    >
      <App>
        <div
          style={{
            minHeight: '100vh',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: isMobile ? 16 : 24,
            background: settings?.publicColorBgBase ?? '#0d1b2a',
          }}
        >
          <Card
            style={{ maxWidth: 400, width: '100%' }}
            styles={{ body: { padding: isMobile ? 20 : 24 } }}
          >
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <TeamOutlined style={{ fontSize: 40, color: settings?.publicColorPrimary ?? '#3498db', marginBottom: 12 }} />
              <Title level={4} style={{ margin: 0 }}>
                Join as Volunteer
              </Title>
              <Text type="secondary" style={{ fontSize: 13 }}>
                {settings?.organizationName ?? 'Changemaker Lite'}
              </Text>
            </div>

            {error && (
              <div
                style={{
                  background: 'rgba(255, 77, 79, 0.1)',
                  border: '1px solid rgba(255, 77, 79, 0.3)',
                  borderRadius: 6,
                  padding: '8px 12px',
                  marginBottom: 16,
                  fontSize: 13,
                  color: '#ff4d4f',
                }}
              >
                {error}
              </div>
            )}

            <Form onFinish={handleSubmit} layout="vertical" size="large" requiredMark={false}>
              <Form.Item
                name="email"
                rules={[
                  { required: true, message: 'Email is required' },
                  { type: 'email', message: 'Enter a valid email' },
                ]}
              >
                <Input prefix={<MailOutlined />} placeholder="Your email" autoFocus />
              </Form.Item>

              <Form.Item name="name">
                <Input prefix={<UserOutlined />} placeholder="Your name (optional)" />
              </Form.Item>

              <Form.Item name="phone">
                <Input prefix={<PhoneOutlined />} placeholder="Phone (optional)" />
              </Form.Item>

              <Form.Item style={{ marginBottom: 0 }}>
                <Button type="primary" htmlType="submit" block loading={loading}>
                  Join & Start Canvassing
                </Button>
              </Form.Item>
            </Form>

            <Text type="secondary" style={{ display: 'block', textAlign: 'center', marginTop: 16, fontSize: 11 }}>
              You'll get temporary 24-hour access to the canvassing app.
            </Text>
            <div style={{ textAlign: 'center', marginTop: 12 }}>
              <Button type="link" size="small" icon={<HomeOutlined />} onClick={() => window.location.href = '/campaigns'}>
                Browse Site
              </Button>
            </div>
          </Card>
        </div>
      </App>
    </ConfigProvider>
  );
}
