import React, { useState, useEffect, useCallback } from "react";
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  CircularProgress,
  Alert,
  Typography,
  Table,
  TableHead,
  TableRow,
  TableCell,
  TableBody,
} from "@mui/material";
import { Bar } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
} from "chart.js";

// רישום של כל ה-ChartJS
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip);

interface ReportData {
  totalTime: number;
  averageTime: number;
  averageWaitTime: number;
  peakHours: { hour: string; count: number }[];
}

interface Props {
  open: boolean;
  onClose: () => void;
  userId: string;
}

// המרה למילישניות לדקות ושניות
const convertToTime = (milliseconds: number): string => {
  const totalSeconds = Math.floor(milliseconds / 1000);
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;
  return `${minutes}m ${seconds}s`; // ניתן לשנות את הפורמט בהתאם לצורך
};

export const VehicleReportDialog = ({ open, onClose, userId }: Props) => {
  const [loading, setLoading] = useState<boolean>(false);
  const [report, setReport] = useState<ReportData | null>(null);
  const [error, setError] = useState<string>("");

  // const generateReport = useCallback(async () => {
  //   setLoading(true);
  //   setError("");
  //   try {
  //     const response = await fetch(
  //       `http://localhost:3001/api/report?userId=${encodeURIComponent(userId)}`
  //     );
  //     if (!response.ok) {
  //       let errorMsg = "Failed to fetch report data";
  //       try {
  //         const errorRes = await response.json();
  //         errorMsg = errorRes.message || errorMsg;
  //       } catch {
  //         // אם לא הצליח לקרוא את הודעת השגיאה ב-JSON
  //       }
  //       throw new Error(errorMsg);
  //     }
  //     const data = await response.json();
  //     setReport(data);
  //   } catch (err: any) {
  //     setError(err.message || "Error fetching report data");
  //   } finally {
  //     setLoading(false);
  //   }
  // }, [userId]);
const generateReport = useCallback(async () => {
  setLoading(true);
  setError("");
  try {
    console.log("Fetching report for userId:", userId);
    const response = await fetch(
      `http://localhost:3001/api/report?userId=${encodeURIComponent(userId)}`
    );
    if (!response.ok) {
      let errorMsg = "Failed to fetch report data";
      try {
        const errorRes = await response.json();
        errorMsg = errorRes.message || errorMsg;
      } catch {
        // אם לא הצליח לקרוא את הודעת השגיאה ב-JSON
      }
      throw new Error(errorMsg);
    }
    const data = await response.json();
    console.log("Report data fetched successfully:", data);

    // אם אין זמן כולל, מחשבים את הזמן הנוכחי מהשעה של כניסת החניה
    if (data.totalTime === null) {
      console.log("No totalTime found, calculating it...");
      const entryTime = data.entryTime; // הזמן שהמשתמש נכנס לחניה
      const currentTime = Date.now(); // הזמן הנוכחי
      const totalTime = currentTime - entryTime; // חישוב הזמן שעבר
      data.totalTime = totalTime; // עדכון נתוני הזמן
    }

    setReport(data);
  } catch (err: any) {
    console.error("Error fetching report data:", err);
    setError(err.message || "Error fetching report data");
  } finally {
    setLoading(false);
  }
}, [userId]);


  useEffect(() => {
    if (open) {
      generateReport();
    } else {
      setReport(null);
      setError("");
      setLoading(false);
    }
  }, [open, generateReport]);

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="md"
      fullWidth
      aria-labelledby="vehicle-report-dialog-title"
      aria-describedby="vehicle-report-dialog-description"
    >
      <DialogTitle id="vehicle-report-dialog-title">Vehicle Report</DialogTitle>
      <DialogContent dividers id="vehicle-report-dialog-description">
        {loading ? (
          <CircularProgress />
        ) : error ? (
          <Alert severity="error" role="alert" sx={{ mb: 2 }}>
            {error}
          </Alert>
        ) : report ? (
          <>
            <Typography variant="h6" gutterBottom>
              Total Time: {convertToTime(report.totalTime)} {/* הצגת זמן כולל */}
            </Typography>
            <Typography variant="h6" gutterBottom>
              Average Time: {convertToTime(report.averageTime)} {/* הצגת זמן ממוצע */}
            </Typography>
            <Typography variant="h6" gutterBottom>
              Average Wait Time: {convertToTime(report.averageWaitTime)} {/* הצגת זמן המתנה ממוצע */}
            </Typography>
            <Table aria-label="Peak hours table" size="small">
              <TableHead>
                <TableRow>
                  <TableCell>Hour</TableCell>
                  <TableCell>Count</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {report.peakHours.map((row, i) => (
                  <TableRow key={i}>
                    <TableCell>{row.hour}</TableCell>
                    <TableCell>{row.count}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
            <div style={{ marginTop: 20 }}>
              <Bar
                data={{
                  labels: report.peakHours.map((h) => h.hour),
                  datasets: [
                    {
                      label: "Peak Hours",
                      data: report.peakHours.map((h) => h.count),
                      backgroundColor: "rgba(75, 192, 192, 0.2)",
                      borderColor: "rgba(75, 192, 192, 1)",
                      borderWidth: 1,
                    },
                  ],
                }}
                options={{
                  responsive: true,
                  plugins: {
                    title: {
                      display: true,
                      text: "Peak Hour Distribution",
                    },
                    tooltip: { enabled: true },
                  },
                  scales: {
                    y: {
                      beginAtZero: true,
                      ticks: {
                        stepSize: 1,
                      },
                    },
                  },
                }}
              />
            </div>
          </>
        ) : (
          <Typography>No data to display.</Typography>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} color="primary">
          Close
        </Button>
      </DialogActions>
    </Dialog>
  );
};

,תעזור ללי שהקוד הזה יציג לי בכל שאילתה מחדש את הזמנים שיתעדכנו!!!!!!!!!!!!!!!!!!!!!!!