import AddIcon from "@mui/icons-material/Add";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import CloseIcon from "@mui/icons-material/Close";
import {
  Box,
  Button,
  Checkbox,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControlLabel,
  IconButton,
  MenuItem,
  Paper,
  TextField,
  Typography,
  Divider,
} from "@mui/material";
import React, { useMemo, useRef, useState } from "react";
import CustomBreadcrumbs from "../../components/CustomBreadcrumbs";
import PageHeader from "../../components/PageHeader";
import { useStyles } from "./paymentStyles";
import Table from "../../components/Table";
import { pushNotification } from "../../utils/notification";
import { NOTIFICATION } from "../../constants";
import { emailRegex } from "../../utils/regex";
import {
  createClinicOffer,
  deleteClinicOffer,
  getClinicOffer,
  updateClinicOffer,
} from "../../services/clinics.service";

const PaymentManagement = () => {
  const classes = useStyles();
  const tableRef = useRef(null);

  // State for payment dialog
  const [paymentDialogOpen, setPaymentDialogOpen] = useState(false);
  const [paymentData, setPaymentData] = useState({
    clinicEmail: "",
    setupFeeWaived: false,
    specialOffer: false,
    configurationMonth: 3,
  });

  // State for payments list
  const [editPaymentId, setEditPaymentId] = useState(null);
  
  // State for delete confirmation dialog
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deletePaymentId, setDeletePaymentId] = useState(null);

  const columns = useMemo(() => [
    {
      size: 100,
      header: "Sr. No.",
      Cell: (props) => {
        const tableState = props?.table?.getState();
        const serialNumber = (
          props?.row?.index +
          1 +
          tableState?.pagination?.pageIndex * tableState?.pagination?.pageSize
        )
          ?.toString()
          ?.padStart(1, "0");
        return <span>{serialNumber}</span>;
      },
      enableSorting: false,
    },
    {
      size: 260,
      accessorKey: "clinic_email",
      header: "Clinic Email",
      enableColumnFilter: false,
    },
    {
      size: 200,
      accessorKey: "setup_fees_waived",
      header: "Setup Fees Waived",
      Cell: (props) => (props.renderedCellValue ? "Yes" : "No"),
      enableColumnFilter: false,
      enableSorting: false,
    },
    {
      size: 200,
      accessorKey: "special_offer_for_month",
      header: "Special Offer For Month",
      enableColumnFilter: false,
      enableSorting: false,
    },
  ]);

  const getData = async (filters) => {
    try {
      let params = {
        ...filters,
      };

      const resp = await getClinicOffer(params);

      return {
        data: resp?.data?.data?.data,
        rowCount: resp?.data?.total || 0,
      };
    } catch (error) {
      console.error("Error fetching admins:", error);
      return {
        data: [],
        rowCount: 0,
      };
    }
  };

  // Handle payment dialog submission (both add and update)
  const handleAddPayment = async () => {
    // Validate input
    if (!paymentData.clinicEmail.trim()) {
      pushNotification("Please enter a clinic email", NOTIFICATION.ERROR);
      return;
    }

    if (!emailRegex.test(paymentData.clinicEmail)) {
      pushNotification("Please enter a valid clinic email", NOTIFICATION.ERROR);
      return;
    }

    // either setup fees waived or special offer for month should be true
    if (!paymentData.setupFeeWaived && !paymentData.specialOffer) {
      pushNotification(
        "Please select either setup fees waived or special offer for month",
        NOTIFICATION.ERROR
      );
      return;
    }

    const payload = {
      clinic_email: paymentData.clinicEmail,
      setup_fees_waived: paymentData.setupFeeWaived,
      special_offer_for_month: paymentData.specialOffer
        ? paymentData.configurationMonth.toString()
        : "0",
    };

    try {

      if (editPaymentId !== null) {
        const resp = await updateClinicOffer(payload, editPaymentId);
      }
      else{
        const resp = await createClinicOffer(payload);
      }

      // Reset form and close dialog
      setPaymentData({
        clinicEmail: "",
        setupFeeWaived: false,
        specialOffer: false,
        configurationMonth: 3,
      });
      setEditPaymentId(null);
      setPaymentDialogOpen(false);
      
      // Refresh the table data
      if (tableRef.current) {
        tableRef.current.reFetchData();
        pushNotification(
          `Payment configuration ${editPaymentId !== null ? 'updated' : 'added'} successfully`, 
          NOTIFICATION.SUCCESS
        );
      }
    } catch (error) {
      console.error("Error saving payment configuration:", error);
      pushNotification(
        `Failed to ${editPaymentId !== null ? 'update' : 'add'} payment configuration`, 
        NOTIFICATION.ERROR
      );
    }
  };

  // Handle edit payment
  const handleEditPayment = (rowData) => {
    // Convert the data from API format to form format
    const formattedData = {
      clinicEmail: rowData.original.clinic_email,
      setupFeeWaived: rowData.original.setup_fees_waived,
      specialOffer: rowData.original.special_offer_for_month !== "0",
      configurationMonth: rowData.original.special_offer_for_month !== "0" ? parseInt(rowData.original.special_offer_for_month) : 3,
    };
    
    setEditPaymentId(rowData.original.id); // Store the ID for update operation
    setPaymentData(formattedData);
    setPaymentDialogOpen(true);
  };

  // Open delete confirmation dialog
  const openDeleteConfirmation = (id) => {
    setDeletePaymentId(id);
    setDeleteDialogOpen(true);
  };

  const handleDialog = () => {
    setPaymentDialogOpen(!paymentDialogOpen);
    setPaymentData({
      clinicEmail: "",
      setupFeeWaived: false,
      specialOffer: false,
      configurationMonth: 3,
    });
    setEditPaymentId(null);
  };

  // Handle delete payment after confirmation
  const handleDeletePayment = async () => {
    try {
      const resp = await deleteClinicOffer(deletePaymentId);
      pushNotification(
        "Payment configuration deleted successfully", 
        NOTIFICATION.SUCCESS
      );
    } catch (error) {
      console.error("Error deleting payment configuration:", error);
      pushNotification(
        `Failed to delete payment configuration`, 
        NOTIFICATION.ERROR
      );
    }

    // Close the dialog and refresh the table
    setDeleteDialogOpen(false);
    setDeletePaymentId(null);
    
    if (tableRef.current) {
      tableRef.current.reFetchData();
    }
  };

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

  return (
    <>
      <Box>
        <PageHeader
          pageTitle="Payment Management"
          addButtonIcon={<AddIcon />}
          onAddButtonClick={handleDialog}
        />
        <CustomBreadcrumbs breadcrumbs={breadcrumbs} />
        <Box className={classes.tableMainDiv}>
          <Box>
            <Table
              ref={tableRef}
              hideTopToolbar
              columns={columns}
              getData={getData}
              options={{
                enableRowSelection: false,
                showTopBar: false,
                showFilters: true,
              }}
              showAction={true}
              searchText="Clinics"
              showSearchBox={true}
              actions={[
                {
                  onClick: (row) => handleEditPayment(row),
                  text: "Edit",
                  icon: (<EditIcon alt="Edit" />),
                },
                {
                  onClick: (row) => openDeleteConfirmation(row.original.id),
                  text: "Delete",
                  icon: (<DeleteIcon alt="Delete" />),
                },
              ]}
            />
          </Box>
        </Box>

        {/* Improved Dialog Box */}
        <Dialog
          open={paymentDialogOpen}
          onClose={handleDialog}
          maxWidth="sm"
          fullWidth
          PaperProps={{
            sx: {
              borderRadius: "12px",
              overflow: "hidden",
            },
          }}
        >
          <DialogTitle
            sx={{
              padding: "16px 24px",
              backgroundColor: (theme) => theme.palette.primary.main,
              color: "white",
              fontWeight: "bold",
              position: "relative",
            }}
          >
            {editPaymentId !== null
              ? "Edit Payment Configuration"
              : "Add New Payment"}
            <IconButton
              aria-label="close"
              onClick={handleDialog}
              sx={{
                position: "absolute",
                right: 8,
                top: 8,
                color: "white",
              }}
            >
              <CloseIcon />
            </IconButton>
          </DialogTitle>

          <DialogContent sx={{ padding: "24px 24px 16px" }}>
            <Box component="form" sx={{ mt: 1 }}>
              <Typography variant="subtitle2" gutterBottom sx={{ mb: 1 }}>
                Clinic Information
              </Typography>

              <TextField
                autoFocus
                margin="dense"
                id="clinicEmail"
                label="Clinic Email"
                type="text"
                fullWidth
                variant="outlined"
                value={paymentData.clinicEmail}
                onChange={(e) =>
                  setPaymentData({
                    ...paymentData,
                    clinicEmail: e.target.value,
                  })
                }
                sx={{ mb: 3 }}
              />

              <Typography variant="subtitle2" gutterBottom sx={{ mb: 1 }}>
                Payment Options
              </Typography>

              <Paper
                elevation={0}
                sx={{
                  backgroundColor: (theme) => theme.palette.grey[50],
                  p: 2,
                  mb: 2,
                  border: "1px solid",
                  borderColor: (theme) => theme.palette.grey[200],
                  borderRadius: "8px",
                }}
              >
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={paymentData.setupFeeWaived}
                      onChange={(e) =>
                        setPaymentData({
                          ...paymentData,
                          setupFeeWaived: e.target.checked,
                        })
                      }
                      color="primary"
                    />
                  }
                  label={
                    <Box>
                      <Typography variant="body1">Setup fee waived</Typography>
                      <Typography variant="caption" color="text.secondary">
                        No initial setup fee will be charged
                      </Typography>
                    </Box>
                  }
                  sx={{ mb: 1, display: "flex", alignItems: "flex-start" }}
                />

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

                <FormControlLabel
                  control={
                    <Checkbox
                      checked={paymentData.specialOffer}
                      onChange={(e) =>
                        setPaymentData({
                          ...paymentData,
                          specialOffer: e.target.checked,
                        })
                      }
                      color="primary"
                    />
                  }
                  label={
                    <Box>
                      <Typography variant="body1">Special Offer</Typography>
                      <Typography variant="caption" color="text.secondary">
                        First 3 months free of charge
                      </Typography>
                    </Box>
                  }
                  sx={{ display: "flex", alignItems: "flex-start" }}
                />
              </Paper>

              {paymentData.specialOffer && (
                <TextField
                  select
                  margin="dense"
                  id="configurationMonth"
                  label="Configuration Month"
                  fullWidth
                  variant="outlined"
                  value={paymentData.configurationMonth}
                  onChange={(e) =>
                    setPaymentData({
                      ...paymentData,
                      configurationMonth: parseInt(e.target.value),
                    })
                  }
                  sx={{ mt: 1 }}
                  helperText="Number of months for special configuration"
                >
                  {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map((month) => (
                    <MenuItem key={month} value={month}>
                      {month} {month === 1 ? "month" : "months"}
                    </MenuItem>
                  ))}
                </TextField>
              )}
            </Box>
          </DialogContent>

          <DialogActions
            sx={{
              padding: "16px 24px",
              borderTop: "1px solid",
              borderColor: (theme) => theme.palette.grey[200],
              justifyContent: "space-between",
            }}
          >
            <Button
              onClick={() => setPaymentDialogOpen(false)}
              sx={{
                color: (theme) => theme.palette.grey[700],
                fontWeight: "medium",
              }}
            >
              Cancel
            </Button>
            <Button
              onClick={handleAddPayment}
              variant="contained"
              color="primary"
              sx={{
                borderRadius: "8px",
                px: 3,
              }}
            >
              {editPaymentId !== null ? "Update" : "Save"}
            </Button>
          </DialogActions>
        </Dialog>

        {/* Delete Confirmation Dialog */}
        <Dialog
          open={deleteDialogOpen}
          onClose={() => setDeleteDialogOpen(false)}
          maxWidth="xs"
          fullWidth
          PaperProps={{
            sx: {
              borderRadius: "12px",
              overflow: "hidden",
            },
          }}
        >
          <DialogTitle
            sx={{
              padding: "16px 24px",
              backgroundColor: (theme) => theme.palette.error.main,
              color: "white",
              fontWeight: "bold",
              position: "relative",
            }}
          >
            Confirm Deletion
            <IconButton
              aria-label="close"
              onClick={() => setDeleteDialogOpen(false)}
              sx={{
                position: "absolute",
                right: 8,
                top: 8,
                color: "white",
              }}
            >
              <CloseIcon />
            </IconButton>
          </DialogTitle>

          <DialogContent sx={{ padding: "24px 24px 16px", mt: 1 }}>
            <Typography variant="body1">
              Are you sure you want to delete this payment configuration? This action cannot be undone.
            </Typography>
          </DialogContent>

          <DialogActions
            sx={{
              padding: "16px 24px",
              borderTop: "1px solid",
              borderColor: (theme) => theme.palette.grey[200],
              justifyContent: "space-between",
            }}
          >
            <Button
              onClick={() => setDeleteDialogOpen(false)}
              sx={{
                color: (theme) => theme.palette.grey[700],
                fontWeight: "medium",
              }}
            >
              Cancel
            </Button>
            <Button
              onClick={handleDeletePayment}
              variant="contained"
              color="error"
              sx={{
                borderRadius: "8px",
                px: 3,
              }}
            >
              Delete
            </Button>
          </DialogActions>
        </Dialog>
      </Box>
    </>
  );
};

export default PaymentManagement;
