import {
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  CircularProgress,
  Container,
  Divider,
  FormControlLabel,
  Grid,
  Paper,
  Radio,
  RadioGroup,
  Stack,
  TextField,
  Typography,
} from '@mui/material';
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import creditcard from '../../assets/images/logo/credit_card.png';
import AccountBalanceIcon from '@mui/icons-material/AccountBalance';
import { NOTIFICATION } from '../../constants';
import { pushNotification } from '../../utils/notification';
import { useNavigate } from 'react-router-dom';
import { setClinicId } from '../../views/ClinicDetails/store/logInAsClinicAdminAction';

const PaymentPage = () => {
  const [paymentMethod, setPaymentMethod] = useState('card');
  const [cardNumber, setCardNumber] = useState('');
  const [accountNumber, setAccountNumber] = useState('');
  const [ifscCode, setIfscCode] = useState('');
  const [bankName, setBankName] = useState('');
  const [cardExpiry, setCardExpiry] = useState('');
  const [cardCVC, setCardCVC] = useState('');
  const [name, setName] = useState('');
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const handleSubmit = (e) => {
    e.preventDefault();
    setLoading(true);

    // Simulate payment processing
    setTimeout(() => {
      setLoading(false);
      setSuccess(true);
    }, 2000);

    pushNotification(
      'Your Account is under review. You will be notified once it is approved.',
      NOTIFICATION.SUCCESS
    );

    // Set clinic admin credentials in Redux store and navigate to login page after 4 seconds
    setTimeout(() => {
      // Dispatch action to set clinic admin credentials
      dispatch(setClinicId({ companyId: 'clinic-admin-123' }));
      navigate('/auth/login');
    }, 4000);
  };

  const formatCardNumber = (value) => {
    const v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');
    const matches = v.match(/\d{4,16}/g);
    const match = (matches && matches[0]) || '';
    const parts = [];

    for (let i = 0; i < match.length; i += 4) {
      parts.push(match.substring(i, i + 4));
    }

    if (parts.length) {
      return parts.join(' ');
    } else {
      return value;
    }
  };

  const formatExpiry = (value) => {
    const v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');

    if (v.length >= 2) {
      return `${v.substring(0, 2)}/${v.substring(2, 4)}`;
    }

    return value;
  };

  return (
    <Container maxWidth="md">
      <Box py={4}>
        <Typography variant="h4" gutterBottom align="center" fontWeight="bold">
          Premium Subscription
        </Typography>

        <Grid container spacing={4} mt={2}>
          <Grid item xs={12} md={7}>
            <Paper
              elevation={0}
              sx={{ p: 3, border: '1px solid #e0e0e0', borderRadius: 2 }}
            >
              {success ? (
                <Box textAlign="center" py={4}>
                  <Typography variant="h5" color="primary" gutterBottom>
                    Payment Successful!
                  </Typography>
                  <Typography variant="body1" color="text.secondary">
                    Thank you for your purchase. You will receive a confirmation
                    email shortly.
                  </Typography>
                </Box>
              ) : (
                <form onSubmit={handleSubmit}>
                  <Typography
                    variant="body2"
                    color="text.secondary"
                    gutterBottom
                  >
                    *Using Stripe Payment Gateway
                  </Typography>

                  <Typography variant="h6" gutterBottom>
                    Payment Method
                  </Typography>

                  <RadioGroup
                    value={paymentMethod}
                    onChange={(e) => setPaymentMethod(e.target.value)}
                  >
                    <Paper
                      variant="outlined"
                      sx={{
                        p: 2,
                        mb: 2,
                        borderColor:
                          paymentMethod === 'card' ? 'primary.main' : 'divider',
                      }}
                    >
                      <FormControlLabel
                        value="card"
                        control={<Radio />}
                        label={
                          <Box display="flex" alignItems="center">
                            <Box
                              component="img"
                              src={creditcard}
                              alt="Credit card icons"
                              sx={{ mr: 1, height: 24, width: 24 }}
                            />
                            <Typography>Credit / Debit Card</Typography>
                          </Box>
                        }
                      />

                      {paymentMethod === 'card' && (
                        <Box mt={2}>
                          <TextField
                            label="Card Number"
                            fullWidth
                            margin="dense"
                            value={cardNumber}
                            onChange={(e) =>
                              setCardNumber(formatCardNumber(e.target.value))
                            }
                            placeholder="1234 5678 9012 3456"
                            inputProps={{ maxLength: 19 }}
                          />

                          <Grid container spacing={2}>
                            <Grid item xs={6}>
                              <TextField
                                label="Expiry Date"
                                fullWidth
                                margin="dense"
                                value={cardExpiry}
                                onChange={(e) =>
                                  setCardExpiry(formatExpiry(e.target.value))
                                }
                                placeholder="MM/YY"
                                inputProps={{ maxLength: 5 }}
                              />
                            </Grid>
                            <Grid item xs={6}>
                              <TextField
                                label="CVC"
                                fullWidth
                                margin="dense"
                                value={cardCVC}
                                onChange={(e) => setCardCVC(e.target.value)}
                                placeholder="123"
                                inputProps={{ maxLength: 3 }}
                              />
                            </Grid>
                          </Grid>

                          <TextField
                            label="Name on Card"
                            fullWidth
                            margin="dense"
                            value={name}
                            onChange={(e) => setName(e.target.value)}
                            placeholder="John Smith"
                          />
                        </Box>
                      )}
                    </Paper>
                    <Paper
                        variant="outlined"
                        sx={{
                          p: 2,
                          mb: 2,
                          mt: 2,
                          borderColor:
                            paymentMethod === 'net_banking' ? 'primary.main' : 'divider',
                        }}
                      >
                        <FormControlLabel
                          value="net_banking"
                          control={<Radio />}
                          label={
                            <Box display="flex" alignItems="center">
                              <AccountBalanceIcon sx={{ mr: 1, height: 24, width: 24 }} />
                              <Typography>Net Banking</Typography>
                            </Box>
                          }
                        />
                        
                      {paymentMethod === 'net_banking' && (
                        <Box mt={2}>
                          <TextField
                            label="Bank Name"
                            fullWidth
                            margin="dense"
                            value={bankName}
                            onChange={(e) => setBankName(e.target.value)}
                            placeholder="Enter Bank Name"
                            required
                          />
                          <TextField
                            label="Account Number"
                            fullWidth
                            margin="dense"
                            value={accountNumber}
                            onChange={(e) => setAccountNumber(e.target.value)}
                            placeholder="Enter Account Number"
                            required
                          />
                          <TextField
                            label="IFSC Code"
                            fullWidth
                            margin="dense"
                            value={ifscCode}
                            onChange={(e) => setIfscCode(e.target.value)}
                            placeholder="Enter IFSC Code"
                            required
                          />
                        </Box>
                      )}

                    </Paper>
                  </RadioGroup>

                  <Button
                    type="submit"
                    variant="contained"
                    fullWidth
                    size="large"
                    disabled={
                      loading ||
                      (paymentMethod === 'card' &&
                        (!cardNumber || !cardExpiry || !cardCVC || !name)) ||
                      (paymentMethod === 'net_banking' &&
                        (!accountNumber || !ifscCode || !bankName))
                    }
                    sx={{ mt: 3 }}
                  >
                    {loading ? (
                      <CircularProgress size={24} color="inherit" />
                    ) : (
                      `Pay $10,000.00`
                    )}
                  </Button>
                </form>
              )}
            </Paper>
          </Grid>

          <Grid item xs={12} md={5}>
            <Card
              elevation={0}
              sx={{ border: '1px solid #e0e0e0', borderRadius: 2 }}
            >
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  Order Summary
                </Typography>
                <Box my={2}>
                  <Paper
                    elevation={0}
                    sx={{ p: 2, backgroundColor: '#f9f9f9', borderRadius: 2 }}
                  >
                    <Stack
                      direction="row"
                      justifyContent="space-between"
                      alignItems="center"
                    >
                      <Box>
                        <Typography variant="subtitle1" fontWeight="bold">
                          Premium Plan
                        </Typography>
                        <Typography variant="body2" color="text.secondary">
                          Annual Subscription
                        </Typography>
                        <Chip
                          label="Yearly"
                          size="small"
                          color="primary"
                          variant="outlined"
                          sx={{ mt: 1 }}
                        />
                      </Box>
                      <Typography variant="h6">$10,000.00</Typography>
                    </Stack>
                  </Paper>
                </Box>

                {/* Payment Information Section */}
                <Typography variant="h6" gutterBottom sx={{ mt: 3 }}>
                  Payment Information
                </Typography>
                <Box mb={2}>
                  <Paper
                    elevation={0}
                    sx={{ p: 2, backgroundColor: '#f9f9f9', borderRadius: 2 }}
                  >
                    <Typography variant="subtitle2" fontWeight="bold" gutterBottom>
                      Subscription Details
                    </Typography>
                    
                    <Stack direction="row" justifyContent="space-between" mb={1}>
                      <Typography variant="body2">Setup Fee</Typography>
                      <Typography variant="body2">$500.00</Typography>
                    </Stack>
                    
                    <Stack direction="row" justifyContent="space-between" mb={1}>
                      <Typography variant="body2">Subscription Fee (Monthly)</Typography>
                      <Typography variant="body2">$800.00</Typography>
                    </Stack>
                    
                    <Stack direction="row" justifyContent="space-between" mb={1}>
                      <Typography variant="body2">Per Call Charges</Typography>
                      <Typography variant="body2">$5.00/call</Typography>
                    </Stack>
                    
                    <Box mt={2}>
                      <Chip
                        label="Special Offer: First 3 months free"
                        size="small"
                        color="secondary"
                        sx={{ mt: 1, mr: 1 }}
                      />
                      <Chip
                        label="Setup fee waived"
                        size="small"
                        color="success"
                        sx={{ mt: 1 }}
                      />
                    </Box>
                  </Paper>
                </Box>

                <Divider sx={{ my: 2 }} />

                <Stack direction="row" justifyContent="space-between" mb={1}>
                  <Typography variant="body1">Subtotal</Typography>
                  <Typography variant="body1">$10,000.00</Typography>
                </Stack>
                <Stack direction="row" justifyContent="space-between" mb={2}>
                  <Typography variant="body2" color="text.secondary">
                    Tax
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    $0.00
                  </Typography>
                </Stack>
                <Divider sx={{ my: 2 }} />
                <Stack direction="row" justifyContent="space-between">
                  <Typography variant="subtitle1" fontWeight="bold">
                    Total
                  </Typography>
                  <Typography variant="subtitle1" fontWeight="bold">
                    $10,000.00
                  </Typography>
                </Stack>

                <Box mt={3}>
                  <Typography
                    variant="body2"
                    color="text.secondary"
                    align="center"
                  >
                    Your subscription will automatically renew after 12 months
                  </Typography>
                </Box>
              </CardContent>
            </Card>

            <Paper
              elevation={0}
              sx={{ p: 2, mt: 2, border: '1px solid #e0e0e0', borderRadius: 2 }}
            >
              <Typography variant="subtitle2" fontWeight="bold" gutterBottom>
                Transaction Information
              </Typography>
              <Typography variant="body2" color="text.secondary" paragraph>
                <strong>Direct Debit:</strong> Payments will be automatically processed on the 1st of each month.
              </Typography>
              <Typography variant="body2" color="text.secondary" paragraph>
                <strong>Billing Cycle:</strong> Monthly/Annual based on your selected plan.
              </Typography>
              <Typography variant="body2" color="text.secondary" paragraph>
                <strong>Secure Payment:</strong> All transactions are encrypted and secure via Stripe Payment Gateway.
              </Typography>
              <Typography variant="body2" color="text.secondary">
                <strong>Customer Support:</strong> If you have any questions,
                please contact our support team at support@healthapps.com
              </Typography>
            </Paper>
          </Grid>
        </Grid>
      </Box>
    </Container>
  );
};

export default PaymentPage;
