"use client";
import React, { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import axios from "axios";
import PageContainer from "@/app/components/container/PageContainer";
import BaseCard from "@/app/components/shared/BaseCard";
import {
  Box,
  Grid,
  Typography,
  Alert,
  LinearProgress,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
} from "@mui/material";
import { DataGrid, GridRenderCellParams } from "@mui/x-data-grid";
import { LocalizationProvider, DateTimePicker } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import dayjs, { Dayjs } from "dayjs";

const DB_FORMAT = "YYYY-MM-DD HH:mm:ss";

export default function ViewSchedulesPage() {
  const { adminId } = useParams();
  const router = useRouter();

  const [schedules, setSchedules] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  // dialog state
  const [openForm, setOpenForm] = useState(false);
  const [openDelete, setOpenDelete] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [deleteId, setDeleteId] = useState<number | null>(null);

  // form state
  const [start, setStart] = useState<Dayjs | null>(null);
  const [end, setEnd] = useState<Dayjs | null>(null);

  // auto clear alerts
  useEffect(() => {
    if (error || success) {
      const t = setTimeout(() => {
        setError(null);
        setSuccess(null);
      }, 3000);
      return () => clearTimeout(t);
    }
  }, [error, success]);

  // load schedules
  const loadSchedules = async () => {
    try {
      setLoading(true);
      const res = await axios.post("/api/schedules", { adminId });
      setSchedules(res.data.data || []);
    } catch {
      setError("Failed to load schedules");
    } finally {
      setLoading(false);
    }
  };

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

  // save schedule
  const handleSave = async () => {
    if (!start || !end || !start.isValid() || !end.isValid()) {
      setError("Please select valid start and end time");
      return;
    }

    if (start.isAfter(end)) {
      setError("End time must be after start time");
      return;
    }

    try {
      setLoading(true);



      if (editing) {
        const payload = {
          start_datetime: start.format(DB_FORMAT),
          end_datetime: end.format(DB_FORMAT),
          id: editing.id,
        };
        await axios.post(`/api/updateSchedule`, payload);
        setSuccess("Schedule updated successfully");
      } else {
        const payload = {
          start_datetime: start.format(DB_FORMAT),
          end_datetime: end.format(DB_FORMAT),
        };
        await axios.post("/api/createSchedule", {
          adminId,
          ...payload,
        });
        setSuccess("Schedule added successfully");
      }

      setOpenForm(false);
      setEditing(null);
      setStart(null);
      setEnd(null);
      loadSchedules();
    } catch {
      setError("Failed to save schedule");
    } finally {
      setLoading(false);
    }
  };

  // delete schedule
  const handleDelete = async () => {
    if (!deleteId) return;

    try {
      setLoading(true);
      await axios.post("/api/deleteSchedule", { id: deleteId });
      setSuccess("Schedule deleted successfully");
      setOpenDelete(false);
      setDeleteId(null);
      loadSchedules();
    } catch {
      setError("Failed to delete schedule");
    } finally {
      setLoading(false);
    }
  };

  // table columns
  const columns = [
    {
      field: "start_time",
      headerName: "Start",
      flex: 1,
      renderCell: (params: GridRenderCellParams) =>
        dayjs(params.value, DB_FORMAT).format("MMM D, YYYY hh:mm A"),
    },
    {
      field: "end_time",
      headerName: "End",
      flex: 1,
      renderCell: (params: GridRenderCellParams) =>
        dayjs(params.value, DB_FORMAT).format("MMM D, YYYY hh:mm A"),
    },
    {
      field: "actions",
      headerName: "Actions",
      flex: 1,
      renderCell: (params: GridRenderCellParams) => (
        <>
          <Button
            size="small"
            onClick={() => {
              setEditing(params.row);
              setStart(dayjs(params.row.start_time, DB_FORMAT));
              setEnd(dayjs(params.row.end_time, DB_FORMAT));
              setOpenForm(true);
            }}
          >
            Edit
          </Button>

          <Button
            size="small"
            color="error"
            onClick={() => {
              setDeleteId(params.row.id);
              setOpenDelete(true);
            }}
            sx={{ ml: 1 }}
          >
            Delete
          </Button>
        </>
      ),
    },
  ];

  return (
    <PageContainer title="Employee Schedules">
      <Grid container spacing={2}>
        <Grid sx={{ width: "100%" }}>
          {error && <Alert severity="error">{error}</Alert>}
          {success && <Alert severity="success">{success}</Alert>}
        </Grid>

        <Grid sx={{ width: "100%" }}>
          <BaseCard title="Schedules">
            <Box sx={{ display: "flex", justifyContent: "space-between", mb: 2 }}>
              <Button variant="outlined" onClick={() => router.back()}>
                Back
              </Button>
              <Button
                variant="contained"
                onClick={() => {
                  setEditing(null);
                  setStart(null);
                  setEnd(null);
                  setOpenForm(true);
                }}
              >
                Add Schedule
              </Button>
            </Box>

            {loading && (
              <>
                <LinearProgress />
                <br />
              </>
            )}

            <Box sx={{ width: "100%" }}>
              <DataGrid
                rows={schedules}
                columns={columns}
                pageSizeOptions={[10, 20]}
                initialState={{
                  pagination: { paginationModel: { pageSize: 10 } },
                }}
                sx={{
                  border: "none",
                  "& .MuiDataGrid-columnHeaders": {
                    backgroundColor: "#f8f8f8",
                    fontWeight: "bold",
                  },
                }}
              />
            </Box>
          </BaseCard>
        </Grid>
      </Grid>

      {/* ADD / EDIT MODAL */}
      <Dialog open={openForm} onClose={() => setOpenForm(false)} fullWidth maxWidth="xs">
        <DialogTitle>{editing ? "Edit Schedule" : "Add Schedule"}</DialogTitle>
        <DialogContent>
          <LocalizationProvider dateAdapter={AdapterDayjs}>
            <DateTimePicker
              label="Start Date & Time"
              value={start}
              onChange={setStart}
              sx={{ mt: 2, width: "100%" }}
            />
            <DateTimePicker
              label="End Date & Time"
              value={end}
              onChange={setEnd}
              sx={{ mt: 2, width: "100%" }}
            />
          </LocalizationProvider>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenForm(false)}>Cancel</Button>
          <Button variant="contained" onClick={handleSave}>
            Save
          </Button>
        </DialogActions>
      </Dialog>

      {/* DELETE CONFIRMATION */}
      <Dialog open={openDelete} onClose={() => setOpenDelete(false)}>
        <DialogTitle>Delete Schedule</DialogTitle>
        <DialogContent>
          <Typography>
            Are you sure you want to delete this schedule?
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenDelete(false)}>Cancel</Button>
          <Button variant="contained" color="error" onClick={handleDelete}>
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </PageContainer>
  );
}
