"use client";

import React, { useEffect, useState } from "react";
import {
  Box,
  Grid,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Button,
  TextField,
  Pagination,
  Dialog,
  DialogTitle,
  DialogContent,
  IconButton,
  LinearProgress,
  Chip,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import axios from "axios";
import moment from "moment-timezone";
import Flatpickr from "react-flatpickr";
import "flatpickr/dist/flatpickr.css";
import { useRouter } from "next/navigation";

import PageContainer from "@/app/components/container/PageContainer";
import BaseCard from "@/app/components/shared/BaseCard";
import { getSession } from "@/utils/sessionData";
import { Checkbox, FormControlLabel } from "@mui/material";
const SERVER_TZ = "UTC";

export default function LeaveApplicationsPage() {
  const router = useRouter();

  /* =====================
     SESSION & ROLE
  ===================== */
  const [session, setSession] = useState<any>(null);
  const isSuper = session?.role === "Super";
  const isAdmin = session?.role === "Admin";

  /* =====================
     DATA
  ===================== */
  const [rows, setRows] = useState<any[]>([]);
  const [selectedRow, setSelectedRow] = useState<any>(null);

  const [page, setPage] = useState(0);
  const [pageSize] = useState(10);
  const [totalPages, setTotalPages] = useState(0);

  const [search, setSearch] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");

  const [loading, setLoading] = useState(false);

  /* =====================
     MODALS
  ===================== */
  const [viewModalOpen, setViewModalOpen] = useState(false);
  const [requestModalOpen, setRequestModalOpen] = useState(false);

  /* =====================
     REQUEST LEAVE STATE
  ===================== */

  const [isMultiDay, setIsMultiDay] = useState(false);
  const [leaveDates, setLeaveDates] = useState<Date[]>([]);
  const [leaveReason, setLeaveReason] = useState("");
  /* =====================
     SESSION CHECK
  ===================== */
  useEffect(() => {
    const s = getSession();
    if (!s?.token || !s?.admin_id) {
      router.push("/login");
      return;
    }
    setSession(s);
  }, []);

  /* =====================
     SEARCH DEBOUNCE
  ===================== */
  useEffect(() => {
    const t = setTimeout(() => setDebouncedSearch(search), 500);
    return () => clearTimeout(t);
  }, [search]);

  /* =====================
     FETCH LEAVES
  ===================== */
  useEffect(() => {
    if (session?.token) fetchLeaves();
  }, [session?.token, page, debouncedSearch]);

  const fetchLeaves = async () => {
    setLoading(true);
    try {
      const res = await axios.post(
        "/api/leaveApplications",
        {
          page: page + 1,
          limit: pageSize,
          search: debouncedSearch,
          id: isAdmin ? session.admin_id : null,
          token: session.token,
        },
        {
          headers: {
            Authorization: `Bearer ${session.token}`,
          },
        }
      );

      setRows(res.data.data || []);
      setTotalPages(res.data.totalPages || 0);
    } finally {
      setLoading(false);
    }
  };

  /* =====================
     TIME AGO
  ===================== */
  const getTimeAgo = (value: string) => {
    if (!value) return "--";
    const input = moment.tz(value, "YYYY-MM-DD HH:mm:ss", SERVER_TZ);
    const now = moment.tz(SERVER_TZ);

    const m = now.diff(input, "minutes");
    const h = now.diff(input, "hours");
    const d = now.diff(input, "days");

    if (m < 1) return "just now";
    if (m < 60) return `${m} minutes ago`;
    if (h < 24) return `${h} hours ago`;
    return `${d} days ago`;
  };

  /* =====================
     SUPER: APPROVE / REJECT
  ===================== */
  const handleDecision = async (type: "approve" | "reject") => {
    if (!selectedRow) return;

    setLoading(true);
    try {
      await axios.post(
        type === "approve" ? "/api/approveLeave" : "/api/rejectLeave",
        { id: selectedRow.id, token: session?.token },
        { headers: { Authorization: `Bearer ${session.token}` } }
      );

      setViewModalOpen(false);
      setSelectedRow(null);
      fetchLeaves();
    } finally {
      setLoading(false);
    }
  };

  /* =====================
     ADMIN: REQUEST LEAVE
  ===================== */
  const submitLeaveRequest = async () => {
    if (!leaveDates.length) return;

    await axios.post(
      "/api/requestLeave",
      {
        from_date: moment(leaveDates[0]).format("YYYY-MM-DD"),
        to_date: moment(
          leaveDates[isMultiDay ? leaveDates.length - 1 : 0]
        ).format("YYYY-MM-DD"),
        is_multi_day: isMultiDay,
        reason: leaveReason,
        token: session?.token
      },
      {
        headers: { Authorization: `Bearer ${session.token}` },
      }
    );

    setRequestModalOpen(false);
    setLeaveDates([]);
    setLeaveReason("");
    setIsMultiDay(false);
    fetchLeaves();
  };

  /* =====================
     RENDER
  ===================== */
  return (
    <PageContainer title="Leave Applications" description="">
      <Grid container spacing={3} sx={{ flexWrap: "wrap" }}>
        <Grid sx={{ width: "100%" }}>
          {loading && <LinearProgress />}

          <BaseCard
            title="Leave Applications"
            searchBar={
              <TextField
                fullWidth
                placeholder="Search..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
              />
            }
          >
            {isAdmin && (
              <Box display="flex" justifyContent="flex-end" mb={2}>
                <Button variant="contained" onClick={() => setRequestModalOpen(true)}>
                  Request Leave
                </Button>
              </Box>
            )}

            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>#</TableCell>
                    <TableCell>Time</TableCell>
                    <TableCell>Employee</TableCell>
                    <TableCell>Leave Days</TableCell>
                    <TableCell>Status</TableCell>
                    {isSuper && <TableCell align="right">Action</TableCell>}
                  </TableRow>
                </TableHead>

                <TableBody>
                  {rows.map((row, i) => (
                    <TableRow key={row.id}>
                      <TableCell>{page * pageSize + i + 1}</TableCell>
                      <TableCell>{getTimeAgo(row.created_at)}</TableCell>
                      <TableCell>{row.admin?.first} {row.admin?.last}</TableCell>
                      <TableCell>
                        {row.leave_day}
                      </TableCell>
                      <TableCell>
                        <Chip
                          label={row.status === "1" ? "Approved" : row.status === "2" ? "Rejected" : "Pending"}
                          color={row.status === "1" ? "success" : row.status === "2" ? "error" : "warning"}
                        />
                      </TableCell>
                      {isSuper && (
                        <TableCell align="right">
                          <Button size="small" onClick={() => { setSelectedRow(row); setViewModalOpen(true); }}>
                            View
                          </Button>
                        </TableCell>
                      )}
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>

            <Box display="flex" justifyContent="center" mt={2}>
              <Pagination count={totalPages} page={page + 1} onChange={(_, p) => setPage(p - 1)} />
            </Box>
          </BaseCard>
        </Grid>
      </Grid>

      {/* SUPER VIEW MODAL */}
      <Dialog open={viewModalOpen} onClose={() => setViewModalOpen(false)} fullWidth maxWidth="sm">
        <DialogTitle>
          Leave Request
          <IconButton sx={{ position: "absolute", right: 8, top: 8 }} onClick={() => setViewModalOpen(false)}>
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent dividers>
          {selectedRow && (
            <>
              <Typography><b>Employee:</b> {selectedRow.admin?.first} {selectedRow.admin?.last}</Typography>
              <Typography><b>Leave:</b> {selectedRow.leave_day}</Typography>
              <Typography><b>Reason:</b> {selectedRow.reason}</Typography>

              {selectedRow.status === "0" && (
                <Box mt={3} display="flex" justifyContent="flex-end" gap={2}>
                  <Button color="error" variant="contained" onClick={() => handleDecision("reject")}>Reject</Button>
                  <Button color="success" variant="contained" onClick={() => handleDecision("approve")}>Approve</Button>
                </Box>
              )}
            </>
          )}
        </DialogContent>
      </Dialog>

      {/* ADMIN REQUEST MODAL */}
      <Dialog open={requestModalOpen} onClose={() => setRequestModalOpen(false)} fullWidth maxWidth="sm">
        <DialogTitle>
          Request Leave
          <IconButton sx={{ position: "absolute", right: 8, top: 8 }} onClick={() => setRequestModalOpen(false)}>
            <CloseIcon />
          </IconButton>
        </DialogTitle>

        <DialogContent dividers>
          <Box display="flex" flexDirection="column" gap={3}>
            {/* MULTI DAY CHECKBOX */}
            <FormControlLabel
              control={
                <Checkbox
                  checked={isMultiDay}
                  onChange={(e) => {
                    setIsMultiDay(e.target.checked);
                    setLeaveDates([]);
                  }}
                />
              }
              label="Multiple days"
            />

            <Flatpickr
              value={leaveDates}
              options={{
                dateFormat: "Y-m-d",
                minDate: "today",
                mode: isMultiDay ? "range" : "single",
                closeOnSelect: !isMultiDay, // 🔥 KEY FIX
              }}
              onChange={(dates) => setLeaveDates(dates)}
              render={({ defaultValue }, ref) => (
                <TextField
                  inputRef={ref}
                  placeholder={isMultiDay ? "Select date range" : "Select date"}
                  fullWidth
                  size="small"
                  defaultValue={defaultValue}
                />
              )}
            />

            <TextField
              label="Reason"
              multiline
              rows={4}
              value={leaveReason}
              onChange={(e) => setLeaveReason(e.target.value)}
            />

            <Box display="flex" justifyContent="flex-end">
              <Button
                variant="contained"
                disabled={leaveDates.length < 1 || !leaveReason}
                onClick={submitLeaveRequest}
              >
                Submit
              </Button>
            </Box>
          </Box>
        </DialogContent>
      </Dialog>
    </PageContainer>
  );
}
