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

const API_BASE = "/api/admin";

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

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

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",
};

interface RawLeaveRequest {
  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;
  reviewed_at?: string;
  users_leave_requests_user_idTousers?: {
    first_name: string;
    last_name: string;
  };
  users_leave_requests_reviewer_idTousers?: {
    first_name: string;
    last_name: string;
  } | null;
}

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

function mapLeaveRequest(raw: RawLeaveRequest): LeaveRequest {
  const user = raw.users_leave_requests_user_idTousers;
  const reviewer = raw.users_leave_requests_reviewer_idTousers;
  return {
    id: raw.id,
    employee_name: user ? `${user.first_name} ${user.last_name}` : "Neznámý",
    leave_type: raw.leave_type,
    date_from: raw.date_from,
    date_to: raw.date_to,
    total_days: raw.total_days,
    total_hours: raw.total_hours,
    status: raw.status,
    notes: raw.notes,
    reviewer_name: reviewer
      ? `${reviewer.first_name} ${reviewer.last_name}`
      : undefined,
    reviewer_note: raw.reviewer_note,
    created_at: raw.created_at,
    reviewed_at: raw.reviewed_at,
  };
}

export default function LeaveApproval() {
  const { hasPermission } = useAuth();
  const alert = useAlert();
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<"pending" | "processed">(
    "pending",
  );
  const [pendingRequests, setPendingRequests] = useState<LeaveRequest[]>([]);
  const [pendingCount, setPendingCount] = useState(0);
  const [processedRequests, setProcessedRequests] = useState<LeaveRequest[]>(
    [],
  );
  const [approveModal, setApproveModal] = useState<{
    open: boolean;
    request: LeaveRequest | null;
  }>({ open: false, request: null });
  const [rejectModal, setRejectModal] = useState<{
    open: boolean;
    request: LeaveRequest | null;
  }>({ open: false, request: null });
  const [rejectNote, setRejectNote] = useState("");
  const [processing, setProcessing] = useState(false);

  useModalLock(rejectModal.open);

  const fetchPending = useCallback(async () => {
    try {
      const response = await apiFetch(
        `${API_BASE}/leave-requests?status=pending`,
      );
      if (response.status === 401) return;
      const result = await response.json();
      if (result.success) {
        const mapped = (result.data as RawLeaveRequest[]).map(mapLeaveRequest);
        setPendingRequests(mapped);
        setPendingCount(result.pagination?.total ?? mapped.length);
      }
    } catch {
      alert.error("Nepodařilo se načíst žádosti");
    }
  }, [alert]);

  const fetchProcessed = useCallback(async () => {
    try {
      const response = await apiFetch(
        `${API_BASE}/leave-requests?status=approved`,
      );
      if (response.status === 401) return;
      const resultApproved = await response.json();

      const response2 = await apiFetch(
        `${API_BASE}/leave-requests?status=rejected`,
      );
      if (response2.status === 401) return;
      const resultRejected = await response2.json();

      const all = [
        ...(resultApproved.success
          ? (resultApproved.data as RawLeaveRequest[]).map(mapLeaveRequest)
          : []),
        ...(resultRejected.success
          ? (resultRejected.data as RawLeaveRequest[]).map(mapLeaveRequest)
          : []),
      ].sort(
        (a: LeaveRequest, b: LeaveRequest) =>
          new Date(b.reviewed_at!).getTime() -
          new Date(a.reviewed_at!).getTime(),
      );

      setProcessedRequests(all);
    } catch {
      alert.error("Nepodařilo se načíst vyřízené žádosti");
    }
  }, [alert]);

  useEffect(() => {
    setLoading(true);
    fetchPending().finally(() => setLoading(false));
  }, [fetchPending]);

  useEffect(() => {
    if (activeTab === "processed" && processedRequests.length === 0) {
      fetchProcessed();
    }
  }, [activeTab, processedRequests.length, fetchProcessed]);

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

  const handleApprove = async () => {
    setProcessing(true);
    try {
      const response = await apiFetch(
        `${API_BASE}/leave-requests/${approveModal.request!.id}`,
        {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ status: "approved" }),
        },
      );
      if (response.status === 401) return;

      const result = await response.json();
      if (result.success) {
        setApproveModal({ open: false, request: null });
        await fetchPending();
        setProcessedRequests([]);
        alert.success("Žádost byla schválena");
      } else {
        alert.error(result.error);
      }
    } catch {
      alert.error("Chyba připojení");
    } finally {
      setProcessing(false);
    }
  };

  const handleReject = async () => {
    if (!rejectNote.trim()) {
      alert.error("Důvod zamítnutí je povinný");
      return;
    }

    setProcessing(true);
    try {
      const response = await apiFetch(
        `${API_BASE}/leave-requests/${rejectModal.request!.id}`,
        {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            status: "rejected",
            reviewer_note: rejectNote,
          }),
        },
      );
      if (response.status === 401) return;

      const result = await response.json();
      if (result.success) {
        setRejectModal({ open: false, request: null });
        setRejectNote("");
        await fetchPending();
        setProcessedRequests([]);
        alert.success("Žádost byla zamítnuta");
      } else {
        alert.error(result.error);
      }
    } catch {
      alert.error("Chyba připojení");
    } finally {
      setProcessing(false);
    }
  };

  if (loading) {
    return (
      <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>
        <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>
    );
  }

  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">Schvalování nepřítomnosti</h1>
          <p className="admin-page-subtitle">
            {pendingCount > 0
              ? `${pendingCount} ${czechPlural(pendingCount, "žádost čeká", "žádosti čekají", "žádostí čeká")} na schválení`
              : "Žádné čekající žádosti"}
          </p>
        </div>
      </motion.div>

      {/* Tabs */}
      <motion.div
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25, delay: 0.06 }}
      >
        <div className="admin-tabs mb-6">
          <button
            className={`admin-tab ${activeTab === "pending" ? "active" : ""}`}
            onClick={() => setActiveTab("pending")}
          >
            Ke schválení
            {pendingCount > 0 && (
              <span
                className="admin-badge badge-pending"
                style={{
                  marginLeft: "0.5rem",
                  fontSize: "0.7rem",
                  padding: "0.15rem 0.5rem",
                }}
              >
                {pendingCount}
              </span>
            )}
          </button>
          <button
            className={`admin-tab ${activeTab === "processed" ? "active" : ""}`}
            onClick={() => setActiveTab("processed")}
          >
            Vyřízené
          </button>
        </div>
      </motion.div>

      {/* Pending Tab */}
      {activeTab === "pending" && (
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.25, delay: 0.08 }}
        >
          {pendingRequests.length === 0 ? (
            <div className="admin-card">
              <div className="admin-card-body">
                <div className="admin-empty-state">
                  <svg
                    width="48"
                    height="48"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="1.5"
                    className="text-muted mb-4"
                  >
                    <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
                    <polyline points="22 4 12 14.01 9 11.01" />
                  </svg>
                  <p>Žádné čekající žádosti</p>
                </div>
              </div>
            </div>
          ) : (
            <div
              style={{ display: "flex", flexDirection: "column", gap: "1rem" }}
            >
              {pendingRequests.map((req) => (
                <div key={req.id} className="admin-card">
                  <div
                    className="admin-card-body"
                    style={{ padding: "1.25rem" }}
                  >
                    <div
                      style={{
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "flex-start",
                        flexWrap: "wrap",
                        gap: "1rem",
                      }}
                    >
                      <div className="flex-1">
                        <div className="flex-row-gap mb-2">
                          <strong style={{ fontSize: "1rem" }}>
                            {req.employee_name}
                          </strong>
                          <span
                            className={`attendance-leave-badge ${leaveTypeClasses[req.leave_type] || ""}`}
                          >
                            {leaveTypeLabels[req.leave_type] || req.leave_type}
                          </span>
                        </div>
                        <div
                          className="text-secondary"
                          style={{
                            display: "flex",
                            gap: "1.5rem",
                            flexWrap: "wrap",
                            fontSize: "0.875rem",
                          }}
                        >
                          <span>
                            <strong>{formatDate(req.date_from)}</strong> —{" "}
                            <strong>{formatDate(req.date_to)}</strong>
                          </span>
                          <span>
                            {req.total_days}{" "}
                            {czechPlural(req.total_days, "den", "dny", "dnů")} (
                            {req.total_hours}h)
                          </span>
                          <span className="text-muted">
                            Podáno: {formatDatetime(req.created_at)}
                          </span>
                        </div>
                        {req.notes && (
                          <div
                            className="text-secondary"
                            style={{
                              marginTop: "0.5rem",
                              fontSize: "0.875rem",
                              fontStyle: "italic",
                            }}
                          >
                            {req.notes}
                          </div>
                        )}
                      </div>
                      <div
                        style={{
                          display: "flex",
                          gap: "0.5rem",
                          flexShrink: 0,
                        }}
                      >
                        <button
                          onClick={() =>
                            setApproveModal({ open: true, request: req })
                          }
                          className="admin-btn admin-btn-sm"
                          style={{
                            background: "var(--success-light)",
                            color: "var(--success)",
                            border: "none",
                          }}
                        >
                          Schválit
                        </button>
                        <button
                          onClick={() =>
                            setRejectModal({ open: true, request: req })
                          }
                          className="admin-btn admin-btn-sm"
                          style={{
                            background: "var(--danger-light)",
                            color: "var(--danger)",
                            border: "none",
                          }}
                        >
                          Zamítnout
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </motion.div>
      )}

      {/* Processed Tab */}
      {activeTab === "processed" && (
        <motion.div
          className="admin-card"
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.25, delay: 0.08 }}
        >
          <div className="admin-card-body">
            {processedRequests.length === 0 ? (
              <div className="admin-empty-state">
                <p>Zatím žádné vyřízené žádosti</p>
              </div>
            ) : (
              <div className="admin-table-responsive">
                <table className="admin-table">
                  <thead>
                    <tr>
                      <th>Zaměstnanec</th>
                      <th>Typ</th>
                      <th>Od</th>
                      <th>Do</th>
                      <th>Dny</th>
                      <th>Stav</th>
                      <th>Schválil</th>
                      <th>Poznámka</th>
                      <th>Vyřízeno</th>
                    </tr>
                  </thead>
                  <tbody>
                    {processedRequests.map((req) => (
                      <tr key={req.id}>
                        <td>
                          <strong>{req.employee_name}</strong>
                        </td>
                        <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>
                          <span
                            className={`admin-badge ${statusClasses[req.status] || ""}`}
                          >
                            {statusLabels[req.status] || req.status}
                          </span>
                        </td>
                        <td>{req.reviewer_name || "—"}</td>
                        <td style={{ maxWidth: "200px" }}>
                          {req.reviewer_note ? (
                            <span title={req.reviewer_note}>
                              {req.reviewer_note.length > 40
                                ? `${req.reviewer_note.substring(0, 40)}...`
                                : req.reviewer_note}
                            </span>
                          ) : (
                            "—"
                          )}
                        </td>
                        <td
                          className="admin-mono"
                          style={{ whiteSpace: "nowrap" }}
                        >
                          {formatDatetime(req.reviewed_at)}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </motion.div>
      )}

      {/* Approve Confirmation */}
      <ConfirmModal
        isOpen={approveModal.open}
        onClose={() => setApproveModal({ open: false, request: null })}
        onConfirm={handleApprove}
        title="Schválit žádost"
        message={
          approveModal.request
            ? `Schválit ${approveModal.request.total_days} ${czechPlural(approveModal.request.total_days, "den", "dny", "dnů")} ${leaveTypeLabels[approveModal.request.leave_type]?.toLowerCase() || ""} pro ${approveModal.request.employee_name}?`
            : ""
        }
        confirmText="Schválit"
        type="info"
        loading={processing}
      />

      {/* Reject Modal */}
      <AnimatePresence>
        {rejectModal.open && (
          <motion.div
            className="admin-modal-overlay"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
          >
            <div
              className="admin-modal-backdrop"
              onClick={() => {
                setRejectModal({ open: false, request: null });
                setRejectNote("");
              }}
            />
            <motion.div
              className="admin-modal"
              initial={{ opacity: 0, scale: 0.95, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 20 }}
              transition={{ duration: 0.2 }}
            >
              <div className="admin-modal-header">
                <h2 className="admin-modal-title">Zamítnout žádost</h2>
              </div>
              <div className="admin-modal-body">
                {rejectModal.request && (
                  <p className="text-secondary mb-4">
                    {rejectModal.request.employee_name} —{" "}
                    {leaveTypeLabels[rejectModal.request.leave_type]},{" "}
                    {formatDate(rejectModal.request.date_from)} —{" "}
                    {formatDate(rejectModal.request.date_to)} (
                    {rejectModal.request.total_days} dnů)
                  </p>
                )}
                <FormField label="Důvod zamítnutí" required>
                  <textarea
                    value={rejectNote}
                    onChange={(e) => setRejectNote(e.target.value)}
                    placeholder="Uveďte důvod zamítnutí..."
                    className="admin-form-textarea"
                    rows={3}
                    autoFocus
                  />
                </FormField>
              </div>
              <div className="admin-modal-footer">
                <button
                  type="button"
                  onClick={() => {
                    setRejectModal({ open: false, request: null });
                    setRejectNote("");
                  }}
                  className="admin-btn admin-btn-secondary"
                  disabled={processing}
                >
                  Zrušit
                </button>
                <button
                  type="button"
                  onClick={handleReject}
                  disabled={processing || !rejectNote.trim()}
                  className="admin-btn admin-btn-primary"
                >
                  {processing ? "Zpracování..." : "Zamítnout"}
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
