import React, { useEffect, useState } from 'react';
import { Card, Button, Modal, Form, Input, Select, Tag, Space, Row, Col, Typography, Grid, Skeleton, Empty, message } from 'antd';
import { CreditCardOutlined, EditOutlined, DeleteOutlined, StarOutlined, StarFilled, PlusOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import api from '../utils/api';
import { colors, spacing, fontSize } from '../theme';

const { Title, Text } = Typography;
const { useBreakpoint } = Grid;
const { Option } = Select;

// Card type colors
const cardTypeColors = {
  'Visa': '#1a1f71',
  'Mastercard': '#eb001b',
  'American Express': '#006fcf',
  'Discover': '#ff6000',
  'default': colors.primary,
};

function Payments() {
  const navigate = useNavigate();
  const screens = useBreakpoint();
  const isLoggedIn = !!localStorage.getItem('token');

  const [cards, setCards] = useState([]);
  const [loading, setLoading] = useState(true);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingCard, setEditingCard] = useState(null);
  const [editLoading, setEditLoading] = useState(false);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [addLoading, setAddLoading] = useState(false);
  const [form] = Form.useForm();
  const [addForm] = Form.useForm();

  useEffect(() => {
    if (!isLoggedIn) {
      navigate('/login');
      return;
    }
    fetchCards();
  }, [isLoggedIn, navigate]);

  const fetchCards = async () => {
    setLoading(true);
    try {
      const response = await api.get('/payment/cards');
      setCards(response.data);
    } catch (error) {
      message.error('Failed to load saved cards');
      console.error('Error fetching cards:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (card) => {
    setEditingCard(card);
    form.setFieldsValue({
      name_on_card: card.name_on_card || '',
      expiration_month: card.expiration_month || '',
      expiration_year: card.expiration_year || '',
      zip_code: card.zip_code || '',
    });
    setEditModalVisible(true);
  };

  const handleEditSubmit = async () => {
    try {
      const values = await form.validateFields();
      setEditLoading(true);

      await api.put(`/payment/cards/${editingCard.id}`, values);
      message.success('Card updated successfully');
      setEditModalVisible(false);
      setEditingCard(null);
      form.resetFields();
      fetchCards();
    } catch (error) {
      if (error.errorFields) {
        return; // Validation error, form will show it
      }
      message.error('Failed to update card');
      console.error('Error updating card:', error);
    } finally {
      setEditLoading(false);
    }
  };

  const handleDelete = (card) => {
    Modal.confirm({
      title: 'Delete Card',
      content: (
        <div style={{ textAlign: 'center', padding: `${spacing.md}px 0` }}>
          <CreditCardOutlined style={{ fontSize: 48, color: cardTypeColors[card.type_of_card] || cardTypeColors.default, marginBottom: spacing.md }} />
          <div style={{ marginBottom: spacing.xs }}>
            <Text strong>{card.type_of_card || 'Card'}</Text>
          </div>
          <div style={{ marginBottom: spacing.md }}>
            <Text>**** **** **** {card.last_four_digits}</Text>
          </div>
          <Text type="secondary">Are you sure you want to delete this card?</Text>
        </div>
      ),
      centered: true,
      okText: 'Delete',
      okType: 'danger',
      cancelText: 'Cancel',
      onOk: async () => {
        try {
          await api.delete(`/payment/cards/${card.id}`);
          message.success('Card deleted successfully');
          fetchCards();
        } catch (error) {
          message.error('Failed to delete card');
          console.error('Error deleting card:', error);
        }
      },
    });
  };

  const handleSetDefault = async (card) => {
    try {
      await api.post(`/payment/cards/${card.id}/set-default`);
      message.success('Default card updated');
      fetchCards();
    } catch (error) {
      message.error('Failed to set default card');
      console.error('Error setting default card:', error);
    }
  };

  const handleAddCard = () => {
    addForm.resetFields();
    setAddModalVisible(true);
  };

  const handleAddSubmit = async () => {
    try {
      const values = await addForm.validateFields();
      setAddLoading(true);

      await api.post('/payment/cards', {
        card_number: values.card_number.replace(/\s/g, ''),
        name_on_card: values.name_on_card,
        expiration_month: values.expiration_month,
        expiration_year: values.expiration_year,
        security_number: values.security_number,
        zip_code: values.zip_code,
      });

      message.success('Card added successfully');
      setAddModalVisible(false);
      addForm.resetFields();
      fetchCards();
    } catch (error) {
      if (error.errorFields) {
        return; // Validation error, form will show it
      }
      const errorMsg = error.response?.data?.detail || 'Failed to add card';
      message.error(errorMsg);
      console.error('Error adding card:', error);
    } finally {
      setAddLoading(false);
    }
  };

  const formatExpirationDate = (month, year) => {
    if (!month || !year) return 'N/A';
    return `${month.padStart(2, '0')}/${year.slice(-2)}`;
  };

  const renderCardVisual = (card) => {
    const cardColor = cardTypeColors[card.type_of_card] || cardTypeColors.default;
    const isMobile = !screens.md;

    return (
      <Card
        key={card.id}
        style={{
          background: `linear-gradient(135deg, ${cardColor} 0%, ${cardColor}dd 100%)`,
          borderRadius: 12,
          marginBottom: spacing.md,
          color: colors.white,
          position: 'relative',
          minHeight: isMobile ? 180 : 200,
        }}
        styles={{
          body: {
            padding: isMobile ? spacing.md : spacing.lg,
            height: '100%',
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'space-between',
          }
        }}
      >
        {/* Default Tag */}
        {card.main_card && (
          <Tag
            color="gold"
            style={{
              position: 'absolute',
              top: spacing.sm,
              right: spacing.sm,
              margin: 0,
            }}
          >
            <StarFilled /> Default
          </Tag>
        )}

        {/* Card Type */}
        <div style={{ marginBottom: spacing.md }}>
          <Text style={{ color: colors.white, fontSize: fontSize.lg, fontWeight: 600 }}>
            {card.type_of_card || 'Credit Card'}
          </Text>
        </div>

        {/* Card Number (masked) */}
        <div style={{ marginBottom: spacing.md }}>
          <Text style={{ color: colors.white, fontSize: isMobile ? fontSize.lg : fontSize.xl, letterSpacing: 2, fontFamily: 'monospace' }}>
            **** **** **** {card.last_four_digits}
          </Text>
        </div>

        {/* Card Details Row */}
        <Row gutter={spacing.md}>
          <Col xs={12} sm={8}>
            <Text style={{ color: 'rgba(255,255,255,0.7)', fontSize: fontSize.xs, display: 'block' }}>
              NAME ON CARD
            </Text>
            <Text style={{ color: colors.white, fontSize: fontSize.sm }}>
              {card.name_on_card || 'N/A'}
            </Text>
          </Col>
          <Col xs={6} sm={4}>
            <Text style={{ color: 'rgba(255,255,255,0.7)', fontSize: fontSize.xs, display: 'block' }}>
              EXPIRES
            </Text>
            <Text style={{ color: colors.white, fontSize: fontSize.sm }}>
              {formatExpirationDate(card.expiration_month, card.expiration_year)}
            </Text>
          </Col>
          <Col xs={6} sm={4}>
            <Text style={{ color: 'rgba(255,255,255,0.7)', fontSize: fontSize.xs, display: 'block' }}>
              ZIP
            </Text>
            <Text style={{ color: colors.white, fontSize: fontSize.sm }}>
              {card.zip_code || 'N/A'}
            </Text>
          </Col>
        </Row>

        {/* Action Buttons */}
        <div style={{ marginTop: spacing.md, display: 'flex', gap: spacing.xs, flexWrap: 'wrap' }}>
          <Button
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(card)}
            style={{ backgroundColor: 'rgba(255,255,255,0.2)', borderColor: 'transparent', color: colors.white }}
          >
            {!isMobile && 'Edit'}
          </Button>
          <Button
            size="small"
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(card)}
            style={{ backgroundColor: 'rgba(255,255,255,0.2)', borderColor: 'transparent', color: colors.white }}
          >
            {!isMobile && 'Delete'}
          </Button>
          {!card.main_card && (
            <Button
              size="small"
              icon={<StarOutlined />}
              onClick={() => handleSetDefault(card)}
              style={{ backgroundColor: 'rgba(255,255,255,0.2)', borderColor: 'transparent', color: colors.white }}
            >
              {!isMobile && 'Set Default'}
            </Button>
          )}
        </div>
      </Card>
    );
  };

  // Generate year options (current year to +10 years)
  const currentYear = new Date().getFullYear();
  const yearOptions = Array.from({ length: 11 }, (_, i) => currentYear + i);

  if (loading) {
    return (
      <div style={{ maxWidth: 800, margin: '0 auto', padding: screens.md ? spacing.lg : spacing.md }}>
        <Title level={2} style={{ marginBottom: spacing.lg }}>
          <CreditCardOutlined style={{ marginRight: spacing.xs }} />
          Saved Payment Methods
        </Title>
        <Row gutter={[spacing.md, spacing.md]}>
          {[1, 2].map((i) => (
            <Col xs={24} md={12} key={i}>
              <Card style={{ borderRadius: 12 }}>
                <Skeleton active paragraph={{ rows: 4 }} />
              </Card>
            </Col>
          ))}
        </Row>
      </div>
    );
  }

  return (
    <div style={{ maxWidth: 800, margin: '0 auto', padding: screens.md ? spacing.lg : spacing.md }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: spacing.lg, flexWrap: 'wrap', gap: spacing.sm }}>
        <Title level={2} style={{ margin: 0 }}>
          <CreditCardOutlined style={{ marginRight: spacing.xs }} />
          Saved Payment Methods
        </Title>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAddCard}
        >
          Add Card
        </Button>
      </div>

      {cards.length === 0 ? (
        <Card style={{ textAlign: 'center', padding: spacing.xl }}>
          <Empty
            image={<CreditCardOutlined style={{ fontSize: 64, color: colors.gray[300] }} />}
            description={
              <span style={{ color: colors.text.secondary }}>
                No saved payment methods
              </span>
            }
          >
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddCard}>
              Add Your First Card
            </Button>
          </Empty>
        </Card>
      ) : (
        <Row gutter={[spacing.md, spacing.md]}>
          {cards.map((card) => (
            <Col xs={24} md={12} key={card.id}>
              {renderCardVisual(card)}
            </Col>
          ))}
        </Row>
      )}

      {/* Edit Modal */}
      <Modal
        title="Edit Card Details"
        open={editModalVisible}
        onOk={handleEditSubmit}
        onCancel={() => {
          setEditModalVisible(false);
          setEditingCard(null);
          form.resetFields();
        }}
        confirmLoading={editLoading}
        centered
        okText="Save Changes"
      >
        <Form
          form={form}
          layout="vertical"
          style={{ marginTop: spacing.md }}
        >
          <Form.Item
            name="name_on_card"
            label="Name on Card"
            rules={[{ required: true, message: 'Please enter the name on card' }]}
          >
            <Input placeholder="John Doe" />
          </Form.Item>

          <Row gutter={spacing.md}>
            <Col xs={12}>
              <Form.Item
                name="expiration_month"
                label="Expiration Month"
                rules={[{ required: true, message: 'Required' }]}
              >
                <Select placeholder="Month">
                  {Array.from({ length: 12 }, (_, i) => i + 1).map((month) => (
                    <Option key={month} value={String(month).padStart(2, '0')}>
                      {String(month).padStart(2, '0')}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col xs={12}>
              <Form.Item
                name="expiration_year"
                label="Expiration Year"
                rules={[{ required: true, message: 'Required' }]}
              >
                <Select placeholder="Year">
                  {yearOptions.map((year) => (
                    <Option key={year} value={String(year)}>
                      {year}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="zip_code"
            label="Billing ZIP Code"
            rules={[{ required: true, message: 'Please enter the billing ZIP code' }]}
          >
            <Input placeholder="12345" maxLength={10} />
          </Form.Item>
        </Form>
      </Modal>

      {/* Add Card Modal */}
      <Modal
        title="Add New Card"
        open={addModalVisible}
        onOk={handleAddSubmit}
        onCancel={() => {
          setAddModalVisible(false);
          addForm.resetFields();
        }}
        confirmLoading={addLoading}
        centered
        okText="Add Card"
      >
        <Form
          form={addForm}
          layout="vertical"
          style={{ marginTop: spacing.md }}
        >
          <Form.Item
            name="card_number"
            label="Card Number"
            rules={[
              { required: true, message: 'Please enter the card number' },
              {
                pattern: /^[\d\s]{13,19}$/,
                message: 'Please enter a valid card number',
              },
            ]}
          >
            <Input
              placeholder="1234 5678 9012 3456"
              maxLength={19}
              onChange={(e) => {
                // Format card number with spaces
                const value = e.target.value.replace(/\s/g, '').replace(/(\d{4})/g, '$1 ').trim();
                addForm.setFieldValue('card_number', value);
              }}
            />
          </Form.Item>

          <Form.Item
            name="name_on_card"
            label="Name on Card"
            rules={[{ required: true, message: 'Please enter the name on card' }]}
          >
            <Input placeholder="John Doe" />
          </Form.Item>

          <Row gutter={spacing.md}>
            <Col xs={8}>
              <Form.Item
                name="expiration_month"
                label="Month"
                rules={[{ required: true, message: 'Required' }]}
              >
                <Select placeholder="MM">
                  {Array.from({ length: 12 }, (_, i) => i + 1).map((month) => (
                    <Option key={month} value={String(month).padStart(2, '0')}>
                      {String(month).padStart(2, '0')}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col xs={8}>
              <Form.Item
                name="expiration_year"
                label="Year"
                rules={[{ required: true, message: 'Required' }]}
              >
                <Select placeholder="YYYY">
                  {yearOptions.map((year) => (
                    <Option key={year} value={String(year)}>
                      {year}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col xs={8}>
              <Form.Item
                name="security_number"
                label="CVV"
                rules={[
                  { required: true, message: 'Required' },
                  { pattern: /^\d{3,4}$/, message: 'Invalid CVV' },
                ]}
              >
                <Input placeholder="123" maxLength={4} />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="zip_code"
            label="Billing ZIP Code"
            rules={[{ required: true, message: 'Please enter the billing ZIP code' }]}
          >
            <Input placeholder="12345" maxLength={10} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default Payments;
