import AddIcon from "@mui/icons-material/Add";
import CloseIcon from "@mui/icons-material/Close";
import {
  Box,
  Button,
  Checkbox,
  Container,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControlLabel,
  IconButton,
  MenuItem,
  Paper,
  Snackbar,
  Alert,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
} from "@mui/material";
import React, { useState } from "react";
import CustomBreadcrumbs from "../../components/CustomBreadcrumbs";
import PageHeader from "../../components/PageHeader";

const PaymentManagement = () => {
  // State for payment dialog
  const [paymentDialogOpen, setPaymentDialogOpen] = useState(false);
  const [paymentData, setPaymentData] = useState({
    clinicName: "",
    setupFeeWaived: false,
    specialOffer: false,
    configurationMonth: 3
  });
  
  // State for payments list
  const [paymentsList, setPaymentsList] = useState([]);
  const [editPaymentIndex, setEditPaymentIndex] = useState(null);

  // State for notification
  const [notification, setNotification] = useState({
    open: false,
    message: "",
    severity: "success",
  });

  // Handle payment dialog submission
  const handleAddPayment = () => {
    // Validate input
    if (!paymentData.clinicName.trim()) {
      setNotification({
        open: true,
        message: "Please enter a clinic name",
        severity: "error",
      });
      return;
    }
    
    if (editPaymentIndex !== null) {
      // Update existing payment
      const updatedPayments = [...paymentsList];
      updatedPayments[editPaymentIndex] = {...paymentData};
      setPaymentsList(updatedPayments);
      
      setNotification({
        open: true,
        message: "Payment configuration updated successfully",
        severity: "success",
      });
    } else {
      // Add new payment
      setPaymentsList([...paymentsList, {...paymentData}]);
      
      setNotification({
        open: true,
        message: "Payment configuration added successfully",
        severity: "success",
      });
    }
    
    // Reset form and close dialog
    setPaymentData({
      clinicName: "",
      setupFeeWaived: false,
      specialOffer: false,
      configurationMonth: 3
    });
    setEditPaymentIndex(null);
    setPaymentDialogOpen(false);
  };
  
  // Handle edit payment
  const handleEditPayment = (index) => {
    setEditPaymentIndex(index);
    setPaymentData({...paymentsList[index]});
    setPaymentDialogOpen(true);
  };
  
  // Handle delete payment
  const handleDeletePayment = (index) => {
    const updatedPayments = [...paymentsList];
    updatedPayments.splice(index, 1);
    setPaymentsList(updatedPayments);
    
    setNotification({
      open: true,
      message: "Payment configuration deleted successfully",
      severity: "success",
    });
  };

  // Handle notification close
  const handleCloseNotification = () => {
    setNotification({
      ...notification,
      open: false,
    });
  };

  // Breadcrumbs
  const breadcrumbs = [
    { label: "Dashboard", link: "/" },
    { label: "Payment Management", link: "/payment-management" },
  ];

  return (
    <Container maxWidth="lg" sx={{ py: 4 }}>
      <PageHeader pageTitle="Payment Management" hideAddButton />

      <CustomBreadcrumbs breadcrumbs={breadcrumbs} />

      <Paper elevation={3} sx={{ p: 0, mb: 4, overflow: "hidden" }}>
        {/* Payment Management Header with Add Button */}
        <Box
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            p: 3,
          }}
        >
          <Typography variant="h6" component="h2" sx={{ fontWeight: "bold" }}>
            Payment Configurations
          </Typography>

          <Button
            variant="contained"
            color="error"
            startIcon={<AddIcon />}
            onClick={() => setPaymentDialogOpen(true)}
            sx={{
              borderRadius: 50,
              textTransform: "none",
              backgroundColor: "#ff3366",
              "&:hover": {
                backgroundColor: "#e61653",
              },
            }}
          >
            Add Payment
          </Button>
        </Box>

        {/* Payment List Table */}
        <TableContainer>
          <Table sx={{ minWidth: 650 }} aria-label="payment table">
            <TableHead sx={{ backgroundColor: "#f5f5f5" }}>
              <TableRow>
                <TableCell sx={{ fontWeight: "bold" }}>Clinic Name</TableCell>
                <TableCell sx={{ fontWeight: "bold" }}>Setup Fee Waived</TableCell>
                <TableCell sx={{ fontWeight: "bold" }}>Special Offer</TableCell>
                <TableCell sx={{ fontWeight: "bold" }}>Configuration Month</TableCell>
                <TableCell sx={{ fontWeight: "bold" }}>Actions</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {paymentsList.length > 0 ? (
                paymentsList.map((payment, index) => (
                  <TableRow key={index}>
                    <TableCell>{payment.clinicName}</TableCell>
                    <TableCell>{payment.setupFeeWaived ? "Yes" : "No"}</TableCell>
                    <TableCell>{payment.specialOffer ? "Yes" : "No"}</TableCell>
                    <TableCell>
                      {payment.specialOffer ? payment.configurationMonth : "-"}
                    </TableCell>
                    <TableCell>
                      <Button
                        size="small"
                        color="primary"
                        onClick={() => handleEditPayment(index)}
                      >
                        Edit
                      </Button>
                      <Button
                        size="small"
                        color="error"
                        onClick={() => handleDeletePayment(index)}
                      >
                        Delete
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={5} align="center">
                    No payment configurations found
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Paper>

      {/* Payment Dialog */}
      <Dialog 
        open={paymentDialogOpen} 
        onClose={() => setPaymentDialogOpen(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          {editPaymentIndex !== null ? "Edit Payment" : "Add New Payment"}
          <IconButton
            aria-label="close"
            onClick={() => setPaymentDialogOpen(false)}
            sx={{
              position: 'absolute',
              right: 8,
              top: 8,
              color: (theme) => theme.palette.grey[500],
            }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent>
          <Box sx={{ mt: 2 }}>
            <TextField
              autoFocus
              margin="dense"
              id="clinicName"
              label="Clinic Name"
              type="text"
              fullWidth
              variant="outlined"
              value={paymentData.clinicName}
              onChange={(e) => setPaymentData({...paymentData, clinicName: e.target.value})}
              sx={{ mb: 2 }}
            />
            
            <FormControlLabel
              control={
                <Checkbox 
                  checked={paymentData.setupFeeWaived} 
                  onChange={(e) => setPaymentData({...paymentData, setupFeeWaived: e.target.checked})}
                />
              }
              label="Setup fee waived"
              sx={{ mb: 1 }}
            />
            
            <FormControlLabel
              control={
                <Checkbox 
                  checked={paymentData.specialOffer} 
                  onChange={(e) => setPaymentData({...paymentData, specialOffer: e.target.checked})}
                />
              }
              label="Special Offer: First 3 months free"
              sx={{ mb: 1 }}
            />
            
            {paymentData.specialOffer && (
              <TextField
                select
                margin="dense"
                id="configurationMonth"
                label="Configuration Month"
                fullWidth
                variant="outlined"
                value={paymentData.configurationMonth}
                onChange={(e) => setPaymentData({...paymentData, configurationMonth: e.target.value})}
                sx={{ mt: 1 }}
              >
                {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map((month) => (
                  <MenuItem key={month} value={month}>
                    {month}
                  </MenuItem>
                ))}
              </TextField>
            )}
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setPaymentDialogOpen(false)} color="primary">
            Cancel
          </Button>
          <Button onClick={handleAddPayment} variant="contained" color="primary">
            Save
          </Button>
        </DialogActions>
      </Dialog>

      {/* Notification Snackbar */}
      <Snackbar
        open={notification.open}
        autoHideDuration={6000}
        onClose={handleCloseNotification}
        anchorOrigin={{ vertical: "top", horizontal: "right" }}
      >
        <Alert
          onClose={handleCloseNotification}
          severity={notification.severity}
          sx={{ width: "100%" }}
        >
          {notification.message}
        </Alert>
      </Snackbar>
    </Container>
  );
};

export default PaymentManagement;