import React, { useState, useEffect } from "react";
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableContainer, 
  TableHead, 
  TableRow, 
  Paper,
  Button,
  TextField,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  MenuItem,
  Select,
  IconButton,
  Typography,
  Box,
  CircularProgress,
  Pagination,
  Chip,
  FormControlLabel,
  Checkbox,
  InputAdornment,
  Tooltip,
  Divider
} from "@mui/material";
import { 
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Settings as SettingsIcon,
  ArrowBack as ArrowBackIcon,
  Search as SearchIcon,
  Close as CloseIcon,
  PlayArrow as PlayArrowIcon,
  ViewColumn as ViewColumnIcon,
  List as ListIcon,
  MoreVert as MoreVertIcon
} from "@mui/icons-material";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import ReportSqlBuilderApi from "APIServices/ReportSQLBuilderAPI";
import { addSQLReport } from "APIServices/AddReportSQLBuilderAPI";
import { UpdateReportSQLBuilder } from "APIServices/UpdateReportSQLBuilderAPI";
import { deleteReportSQL } from "APIServices/DeleteReportSQLAPI";
import ConfirmModal from "../../common/ConfirmModal";
import ReportBuilderService from "../../../APIServices/ReportBuilderService";

function UserDetailsView() {
  const [userDetails, setUserDetails] = useState([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [loading, setLoading] = useState(true);
  const [recordsPerPage, setRecordsPerPage] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);
  const navigate = useNavigate();
  const [showModal, setShowModal] = useState(false);
  const [showAddModal, setShowAddModal] = useState(false);
  const [selectedReport, setSelectedReport] = useState(null);
  const [editData, setEditData] = useState({
    reportName: "",
    description: "",
    active: false,
  });
  const [newData, setNewData] = useState({
    reportName: "",
    description: "",
    active: false,
    isSql: true,
    Rpt_builder2_lines: [{ model: "" }],
  });
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [deleteItem, setDeleteItem] = useState({ index: null, id: null });
  const [showReportConfigModal, setShowReportConfigModal] = useState(false);
  const [reportConfigData, setReportConfigData] = useState({
    conn_name: "",
    date_param_req: "",
    std_param_html: "",
    adhoc_param_html: "",
    column_str: "",
    sql_str: "",
    id: null
  });
  const [databaseConnections, setDatabaseConnections] = useState([]);

  const fetchUserDetails = async () => {
    try {
      setLoading(true);
      const data = await ReportSqlBuilderApi.fetchUserDetails();
      setUserDetails(data);
      toast.success('Data fetched successfully!');
    } catch (error) {
      console.error('Error fetching user details:', error);
      toast.error('Failed to fetch user details.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUserDetails();
  }, []);

  const handlePlayClick = () => {
    if (selectedReport) {
      goToRunner(selectedReport);
    } else {
      toast.error("No report selected to run.");
    }
  };

  const handleRecordsPerPageChange = (event) => {
    setRecordsPerPage(parseInt(event.target.value, 10));
    setCurrentPage(1);
  };

  const handleInputChange = (event) => {
    const { name, value, checked, type } = event.target;
    const inputValue = type === "checkbox" ? checked : value;

    if (showModal) {
      setEditData((prev) => ({ ...prev, [name]: inputValue }));
    } else if (showAddModal) {
      setNewData((prev) => ({ ...prev, [name]: inputValue }));
    }
  };

  const handleSubmit = async () => {
    try {
      const updatedReport = await UpdateReportSQLBuilder(editData.id, editData);
      toast.success("Report Updated successfully..");
      const updatedDetails = userDetails.map((detail) =>
        detail.id === editData.id ? { ...detail, ...editData } : detail
      );
      setUserDetails(updatedDetails);
      setShowModal(false);
    } catch (error) {
      console.error("Error updating the report: ", error);
      toast.error("Failed to update report");
    }
  };

  const filteredUsers = userDetails.filter(
    (item) =>
      item.reportName &&
      item.reportName.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const slicedUsers = filteredUsers.slice(
    (currentPage - 1) * recordsPerPage,
    currentPage * recordsPerPage
  );

  const totalPages = Math.ceil(filteredUsers.length / recordsPerPage);

  const handlePageChange = (event, page) => {
    setCurrentPage(page);
  };

  const handleGoTo = (data) => {
    const hasReportData = data.rpt_builder2_lines?.some(line => line.model && line.model.trim() !== "");
    if (hasReportData) {
      fetchReportConfiguration(data.id, data);
    } else {
      navigate("/admin/reportquery", { state: { id: data.id, reportData: data } });
    }
  };

  const handleRowClick = (report) => {
    fetchReportConfiguration(report.id, report);
  };

  const fetchDatabaseConnections = async () => {
    try {
      setLoading(true);
      const response = await ReportBuilderService.getDatabase();
      if (response && response.data) {
        setDatabaseConnections(response.data);
      } else {
        setDatabaseConnections([]);
      }
    } catch (error) {
      console.error("Error fetching database connections: ", error);
      toast.error("Failed to load database connections");
      setDatabaseConnections([]);
    } finally {
      setLoading(false);
    }
  };

  const fetchReportConfiguration = async (reportId, report) => {
    try {
      setLoading(true);
      const response = await ReportBuilderService.getrbLineDetailsById(report.rpt_builder2_lines[0].id);
      await fetchDatabaseConnections();
      
      if (response && response.data) {
        let configData = {};
        try {
          if (report.Rpt_builder2_lines && report.Rpt_builder2_lines.length > 0) {
            const modelData = JSON.parse(report.Rpt_builder2_lines[0].model);
            configData = {
              conn_name: modelData.conn_name || "",
              date_param_req: modelData.date_param_req || "",
              std_param_html: modelData.std_param_html || "",
              adhoc_param_html: modelData.adhoc_param_html || "",
              column_str: modelData.column_str || "",
              sql_str: modelData.sql_str || "",
              id: report.rpt_builder2_lines[0].id
            };
          } else {
            configData = {
              conn_name: "",
              date_param_req: "",
              std_param_html: "",
              adhoc_param_html: "",
              column_str: "",
              sql_str: "",
              id: report.rpt_builder2_lines[0].id
            };
          }
        } catch (error) {
          console.error("Error parsing report configuration: ", error);
          toast.error("Failed to parse report configuration");
          configData = {
            conn_name: "",
            date_param_req: "",
            std_param_html: "",
            adhoc_param_html: "",
            column_str: "",
            sql_str: "",
            id: report.rpt_builder2_lines[0].id
          };
        }
        setReportConfigData(configData);
        setShowReportConfigModal(true);
      } else {
        toast.error("No configuration data found for this report");
      }
    } catch (error) {
      console.error("Error fetching report configuration: ", error);
      toast.error("Failed to load report configuration");
    } finally {
      setLoading(false);
    }
  };

  const handleReportConfigClose = () => {
    setShowReportConfigModal(false);
  };

  const handleReportConfigChange = (e) => {
    const { name, value } = e.target;
    setReportConfigData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleReportConfigUpdate = async () => {
    try {
      setLoading(true);
      const reportData = {
        conn_name: reportConfigData.conn_name,
        sql_str: reportConfigData.sql_str,
        date_param_req: reportConfigData.date_param_req,
        column_str: reportConfigData.column_str,
        adhoc_param_html: reportConfigData.adhoc_param_html,
        std_param_html: reportConfigData.std_param_html,
      };

      const saveReportData = {
        header_id: reportConfigData.id,
        model: JSON.stringify(reportData),
      };
      
      const response = await ReportBuilderService.updaterbLineData(saveReportData, reportConfigData.id);
      toast.success("Report configuration updated successfully");
      setShowReportConfigModal(false);
      fetchUserDetails();
    } catch (error) {
      console.error("Error updating report configuration: ", error);
      toast.error("Failed to update report configuration");
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    const { id } = deleteItem;
    if (!id) {
      toast.error("Invalid ID. Deletion failed.");
      return;
    }
    
    try {
      const deletedReport = await deleteReportSQL(id);
      toast.success("Report deleted successfully");
      setUserDetails(userDetails.filter(item => item.id !== id));
    } catch (error) {
      console.error("Error in deleting report:", error);
      toast.error("Failed to delete report");
    }
  };

  const confirmDelete = (e, index, id, reportName) => {
    e.stopPropagation();
    setDeleteItem({ index, id, reportName });
    setShowConfirmModal(true);
  };

  const handleEdit = (detail) => {
    setEditData(detail);
    setShowModal(true);
  };

  const handleClose = () => {
    setShowModal(false);
  };

  const handleAddClose = () => {
    setShowAddModal(false);
  };

  const handleAddSubmit = async () => {
    try {
      const addedReport = await addSQLReport(newData);
      setUserDetails((prevUserDetails) => [...prevUserDetails, addedReport]);
      setNewData({ 
        reportName: "", 
        description: "", 
        active: false,
        isSql: true
      });
      setShowAddModal(false);
      toast.success("User report added successfully!");
    } catch (error) {
      toast.error("Failed to add the user report. Please try again.");
      console.error("Error adding user report: ", error);
    }
  };

  const goToRunner = (report) => {
    if (!report || typeof report.isSql === "undefined") {
      console.error("Invalid report object:", report);
      return;
    }

    if (report.isSql) {
      navigate(`/admin/report-runner/${report.id}`);
    } else {
      navigate(`/admin/report-runner2/${report.id}`);
    }
  };

  return (
    <Box sx={{ p: 4 }}>
      <Box sx={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center', 
        mb: 4 
      }}>
        <Typography variant="h4" component="h2">
          Report Builder (SQL)
        </Typography>
        <Box sx={{ display: 'flex', gap: 2 }}>
          <Button 
            variant="contained" 
            startIcon={<PlayArrowIcon />}
            onClick={() => navigate('/admin/report-runner')}
          >
            Report Runner
          </Button>
          <Button 
            variant="contained" 
            startIcon={<AddIcon />}
            onClick={() => setShowAddModal(true)}
          >
            Add
          </Button>
        </Box>
      </Box>

      <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 3 }}>
        <TextField
          placeholder="Search"
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon />
              </InputAdornment>
            ),
            endAdornment: searchQuery && (
              <InputAdornment position="end">
                <IconButton onClick={() => setSearchQuery("")}>
                  <CloseIcon fontSize="small" />
                </IconButton>
              </InputAdornment>
            ),
          }}
          sx={{ width: '50%' }}
        />
      </Box>

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
          <CircularProgress />
        </Box>
      ) : (
        <>
          <TableContainer component={Paper} sx={{ mb: 3 }}>
            <Table>
              <TableHead>
                <TableRow sx={{ backgroundColor: 'primary.main' }}>
                  <TableCell sx={{ color: 'white', fontWeight: 'bold' }}>Go To</TableCell>
                  <TableCell sx={{ color: 'white', fontWeight: 'bold' }}>Report Name</TableCell>
                  <TableCell sx={{ color: 'white', fontWeight: 'bold' }}>Description</TableCell>
                  <TableCell sx={{ color: 'white', fontWeight: 'bold' }}>Status</TableCell>
                  <TableCell sx={{ color: 'white', fontWeight: 'bold' }}>Actions</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {slicedUsers.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={5} align="center">
                      No records found.
                    </TableCell>
                  </TableRow>
                ) : (
                  slicedUsers.filter((detail) => detail.isSql).map((detail, index) => (
                    <TableRow
                      key={index}
                      hover
                      onClick={() => handleRowClick(detail)}
                      sx={{ cursor: 'pointer' }}
                    >
                      <TableCell>
                        <IconButton
                          onClick={(e) => {
                            e.stopPropagation();
                            handleGoTo(detail);
                          }}
                        >
                          <SettingsIcon color="primary" />
                        </IconButton>
                      </TableCell>
                      <TableCell>{detail.reportName}</TableCell>
                      <TableCell>{detail.description || "No description available"}</TableCell>
                      <TableCell>
                        <Chip 
                          label={detail.active ? "Active" : "Inactive"} 
                          color={detail.active ? "success" : "error"} 
                          size="small"
                        />
                      </TableCell>
                      <TableCell>
                        <IconButton
                          onClick={(e) => {
                            e.stopPropagation();
                            handleEdit(detail);
                          }}
                        >
                          <EditIcon color="primary" />
                        </IconButton>
                        <IconButton
                          onClick={(e) => {
                            e.stopPropagation();
                            confirmDelete(e, index, detail.id, detail.reportName);
                          }}
                        >
                          <DeleteIcon color="error" />
                        </IconButton>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>

          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <Typography variant="body2">
                Rows per page:
              </Typography>
              <Select
                value={recordsPerPage}
                onChange={handleRecordsPerPageChange}
                size="small"
                sx={{ height: '36px' }}
              >
                {[5, 10, 25, 50].map((option) => (
                  <MenuItem key={option} value={option}>
                    {option}
                  </MenuItem>
                ))}
              </Select>
            </Box>
            <Pagination
              count={totalPages}
              page={currentPage}
              onChange={handlePageChange}
              color="primary"
              showFirstButton
              showLastButton
            />
          </Box>
        </>
      )}

      {/* Edit Dialog */}
      <Dialog open={showModal} onClose={handleClose} maxWidth="sm" fullWidth>
        <DialogTitle>Edit User Detail</DialogTitle>
        <DialogContent>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mt: 2 }}>
            <TextField
              label="Report Name"
              name="reportName"
              value={editData.reportName || ""}
              onChange={handleInputChange}
              fullWidth
            />
            <TextField
              label="Description"
              name="description"
              value={editData.description || ""}
              onChange={handleInputChange}
              fullWidth
              multiline
              rows={3}
            />
            <FormControlLabel
              control={
                <Checkbox
                  name="active"
                  checked={editData.active || false}
                  onChange={handleInputChange}
                />
              }
              label="Active"
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose}>Cancel</Button>
          <Button onClick={handleSubmit} variant="contained">Save Changes</Button>
        </DialogActions>
      </Dialog>

      {/* Add Dialog */}
      <Dialog open={showAddModal} onClose={handleAddClose} maxWidth="sm" fullWidth>
        <DialogTitle>Add New User Detail</DialogTitle>
        <DialogContent>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mt: 2 }}>
            <TextField
              label="Report Name"
              name="reportName"
              value={newData.reportName}
              onChange={handleInputChange}
              fullWidth
              required
            />
            <TextField
              label="Description"
              name="description"
              value={newData.description}
              onChange={handleInputChange}
              fullWidth
              multiline
              rows={3}
              required
            />
            <FormControlLabel
              control={
                <Checkbox
                  name="active"
                  checked={newData.active}
                  onChange={handleInputChange}
                />
              }
              label="Active"
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleAddClose}>Cancel</Button>
          <Button onClick={handleAddSubmit} variant="contained">Add User Detail</Button>
        </DialogActions>
      </Dialog>

      {/* Confirmation Dialog */}
      <ConfirmModal
        open={showConfirmModal}
        onClose={() => setShowConfirmModal(false)}
        onConfirm={handleDelete}
        title="Confirm Deletion"
        message={`Are you sure you want to delete "${deleteItem.reportName || 'this report'}"? This action cannot be undone.`}
        confirmText="Delete"
        cancelText="Cancel"
      />

      {/* Report Configuration Dialog */}
      <Dialog open={showReportConfigModal} onClose={handleReportConfigClose} maxWidth="md" fullWidth>
        <DialogTitle>Report Configuration</DialogTitle>
        <DialogContent>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, mt: 2 }}>
            <Box sx={{ display: 'flex', gap: 2 }}>
              <Select
                label="Connection Name"
                name="conn_name"
                value={reportConfigData.conn_name}
                onChange={handleReportConfigChange}
                fullWidth
                sx={{ mb: 2 }}
              >
                <MenuItem value="">Select Database Connection</MenuItem>
                {databaseConnections.map((db, index) => (
                  <MenuItem key={index} value={db.name}>
                    {db.name}
                  </MenuItem>
                ))}
              </Select>
              <Select
                label="Date Parameter Required"
                name="date_param_req"
                value={reportConfigData.date_param_req}
                onChange={handleReportConfigChange}
                fullWidth
                sx={{ mb: 2 }}
              >
                <MenuItem value="">Select Option</MenuItem>
                <MenuItem value="Yes">Yes</MenuItem>
                <MenuItem value="No">No</MenuItem>
              </Select>
            </Box>
            
            <TextField
              label="SQL String"
              name="sql_str"
              value={reportConfigData.sql_str}
              onChange={handleReportConfigChange}
              fullWidth
              multiline
              rows={5}
              sx={{ fontFamily: 'monospace' }}
            />
            
            <TextField
              label="Column String (html)"
              name="column_str"
              value={reportConfigData.column_str}
              onChange={handleReportConfigChange}
              fullWidth
              multiline
              rows={3}
            />
            
            <Box sx={{ display: 'flex', gap: 2 }}>
              <TextField
                label="Standard Parameter String (html)"
                name="std_param_html"
                value={reportConfigData.std_param_html}
                onChange={handleReportConfigChange}
                fullWidth
                multiline
                rows={3}
              />
              <TextField
                label="Adhoc Parameter String (html)"
                name="adhoc_param_html"
                value={reportConfigData.adhoc_param_html}
                onChange={handleReportConfigChange}
                fullWidth
                multiline
                rows={3}
              />
            </Box>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleReportConfigClose}>Cancel</Button>
          <Button 
            onClick={handleReportConfigUpdate} 
            variant="contained"
            disabled={loading}
          >
            {loading ? <CircularProgress size={24} /> : 'Update Configuration'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

export default UserDetailsView;