import { useState, useEffect, useCallback } from "react";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import { motion } from "framer-motion";
import Forbidden from "../components/Forbidden";
import { formatDate, formatDatetime } from "../utils/attendanceHelpers";
import apiFetch from "../utils/api";
import ConfirmModal from "../components/ConfirmModal";

const API_BASE = "/api/admin";

const leaveTypeLabels: Record<string, string> = {
  vacation: "Dovolená",
  sick: "Nemoc",
  unpaid: "Neplacené volno",
};

const statusLabels: Record<string, string> = {
  pending: "Čeká na schválení",
  approved: "Schváleno",
  rejected: "Zamítnuto",
  cancelled: "Zrušeno",
};

const statusClasses: Record<string, string> = {
  pending: "badge-pending",
  approved: "badge-approved",
  rejected: "badge-rejected",
  cancelled: "badge-cancelled",
};

const leaveTypeClasses: Record<string, string> = {
  vacation: "badge-vacation",
  sick: "badge-sick",
  unpaid: "badge-unpaid",
};

interface LeaveRequest {
  id: number;
  leave_type: string;
  date_from: string;
  date_to: string;
  total_days: number;
  total_hours: number;
  status: string;
  notes?: string;
  reviewer_note?: string;
  created_at: string;
}

export default function LeaveRequests() {
  const alert = useAlert();
  const { hasPermission } = useAuth();
  const [loading, setLoading] = useState(true);
  const [requests, setRequests] = useState<LeaveRequest[]>([]);
  const [cancelModal, setCancelModal] = useState<{
    open: boolean;
    id: number | null;
  }>({ open: false, id: null });
  const [cancelling, setCancelling] = useState(false);

  const fetchRequests = useCallback(async () => {
    try {
      const response = await apiFetch(`${API_BASE}/leave-requests?mine=1`);
      if (response.status === 401) return;
      const result = await response.json();
      if (result.success) {
        setRequests(result.data);
      }
    } catch {
      alert.error("Nepodařilo se načíst žádosti");
    } finally {
      setLoading(false);
    }
  }, [alert]);

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

  if (!hasPermission("attendance.record")) return <Forbidden />;

  const handleCancel = async () => {
    setCancelling(true);
    try {
      const response = await apiFetch(
        `${API_BASE}/leave-requests/${cancelModal.id}`,
        {
          method: "DELETE",
        },
      );
      if (response.status === 401) return;

      const result = await response.json();
      if (result.success) {
        setCancelModal({ open: false, id: null });
        await fetchRequests();
        alert.success(result.message);
      } else {
        alert.error(result.error);
      }
    } catch {
      alert.error("Chyba připojení");
    } finally {
      setCancelling(false);
    }
  };

  if (loading) {
    return (
      <div>
        <div className="admin-skeleton" style={{ padding: 0, gap: "1.5rem" }}>
          <div
            className="admin-skeleton-row"
            style={{ justifyContent: "space-between" }}
          >
            <div>
              <div
                className="admin-skeleton-line h-8"
                style={{ width: "200px", marginBottom: "0.5rem" }}
              />
              <div className="admin-skeleton-line" style={{ width: "140px" }} />
            </div>
            <div
              className="admin-skeleton-line h-10"
              style={{ width: "140px", borderRadius: "8px" }}
            />
          </div>
          <div className="admin-card">
            <div className="admin-skeleton" style={{ gap: "1.25rem" }}>
              {[0, 1, 2, 3, 4].map((i) => (
                <div key={i} className="admin-skeleton-row">
                  <div className="admin-skeleton-line circle" />
                  <div className="flex-1">
                    <div className="admin-skeleton-line w-1/3 mb-2" />
                    <div
                      className="admin-skeleton-line w-1/4"
                      style={{ height: "10px" }}
                    />
                  </div>
                  <div className="admin-skeleton-line w-1/4" />
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  function renderNoteCell(req: LeaveRequest) {
    const truncate = (text: string) =>
      text.length > 40 ? `${text.substring(0, 40)}...` : text;
    if (req.status === "rejected" && req.reviewer_note) {
      return (
        <span
          style={{ color: "var(--danger)", fontSize: "0.875rem" }}
          title={req.reviewer_note}
        >
          {truncate(req.reviewer_note)}
        </span>
      );
    }
    if (req.notes) {
      return (
        <span
          className="text-secondary"
          style={{ fontSize: "0.875rem" }}
          title={req.notes}
        >
          {truncate(req.notes)}
        </span>
      );
    }
    return <span className="text-muted">—</span>;
  }

  return (
    <div>
      <motion.div
        className="admin-page-header"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25 }}
      >
        <div>
          <h1 className="admin-page-title">Moje žádosti</h1>
          <p className="admin-page-subtitle">Přehled žádostí o nepřítomnost</p>
        </div>
      </motion.div>

      <motion.div
        className="admin-card"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25, delay: 0.06 }}
      >
        <div className="admin-card-body">
          {requests.length === 0 ? (
            <div className="admin-empty-state">
              <div className="admin-empty-icon">
                <svg
                  width="28"
                  height="28"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
                  <line x1="16" y1="2" x2="16" y2="6" />
                  <line x1="8" y1="2" x2="8" y2="6" />
                  <line x1="3" y1="10" x2="21" y2="10" />
                </svg>
              </div>
              <p>Zatím nemáte žádné žádosti</p>
              <p style={{ fontSize: "0.875rem", color: "var(--text-muted)" }}>
                Novou žádost můžete podat na stránce Docházka
              </p>
            </div>
          ) : (
            <div className="admin-table-responsive">
              <table className="admin-table">
                <thead>
                  <tr>
                    <th>Typ</th>
                    <th>Od</th>
                    <th>Do</th>
                    <th>Dny</th>
                    <th>Hodiny</th>
                    <th>Stav</th>
                    <th>Poznámka</th>
                    <th>Podáno</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {requests.map((req) => (
                    <tr key={req.id}>
                      <td>
                        <span
                          className={`attendance-leave-badge ${leaveTypeClasses[req.leave_type] || ""}`}
                        >
                          {leaveTypeLabels[req.leave_type] || req.leave_type}
                        </span>
                      </td>
                      <td className="admin-mono">
                        {formatDate(req.date_from)}
                      </td>
                      <td className="admin-mono">{formatDate(req.date_to)}</td>
                      <td className="admin-mono">{req.total_days}</td>
                      <td className="admin-mono">{req.total_hours}h</td>
                      <td>
                        <span
                          className={`admin-badge ${statusClasses[req.status] || ""}`}
                        >
                          {statusLabels[req.status] || req.status}
                        </span>
                      </td>
                      <td style={{ maxWidth: "200px" }}>
                        {renderNoteCell(req)}
                      </td>
                      <td
                        className="admin-mono"
                        style={{ whiteSpace: "nowrap" }}
                      >
                        {formatDatetime(req.created_at)}
                      </td>
                      <td>
                        {req.status === "pending" && (
                          <button
                            onClick={() =>
                              setCancelModal({ open: true, id: req.id })
                            }
                            className="admin-btn admin-btn-secondary admin-btn-sm"
                          >
                            Zrušit
                          </button>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </motion.div>

      <ConfirmModal
        isOpen={cancelModal.open}
        onClose={() => setCancelModal({ open: false, id: null })}
        onConfirm={handleCancel}
        title="Zrušit žádost"
        message="Opravdu chcete zrušit tuto žádost o nepřítomnost?"
        confirmText="Zrušit žádost"
        type="warning"
        loading={cancelling}
      />
    </div>
  );
}
