"use client";

import { useState, useEffect, useCallback } from "react";
import {
  AlertCircle,
  CheckCircle,
  XCircle,
  Clock,
  User,
  Calendar,
  Phone,
  Mail,
  CalendarPlus,
  AlertTriangle,
  FileText,
  ChevronDown,
} from "lucide-react";
import logger from "@/lib/logger";
import type {
  VoiceAction,
  VoiceActionStatus,
} from "@/lib/types/voice-agent-staff.types";

interface StaffMember {
  id: string;
  name: string;
}

interface NextActionsPanelProps {
  staffMembers: StaffMember[];
  onActionUpdated: () => void;
}

const statusColors: Record<VoiceActionStatus, string> = {
  PENDING: "bg-yellow-100 text-yellow-800 border-yellow-200",
  IN_PROGRESS: "bg-blue-100 text-blue-800 border-blue-200",
  COMPLETED: "bg-green-100 text-green-800 border-green-200",
  DISMISSED: "bg-gray-100 text-gray-600 border-gray-200",
};

const typeIcons: Record<string, React.ReactNode> = {
  CALL_BACK: <Phone className="w-4 h-4" />,
  SEND_EMAIL: <Mail className="w-4 h-4" />,
  BOOK_APPOINTMENT: <CalendarPlus className="w-4 h-4" />,
  ESCALATE: <AlertTriangle className="w-4 h-4" />,
  CUSTOM: <FileText className="w-4 h-4" />,
};

const typeColors: Record<string, string> = {
  CALL_BACK: "bg-purple-100 text-purple-700",
  SEND_EMAIL: "bg-blue-100 text-blue-700",
  BOOK_APPOINTMENT: "bg-green-100 text-green-700",
  ESCALATE: "bg-red-100 text-red-700",
  CUSTOM: "bg-gray-100 text-gray-700",
};

function formatDueDate(dateString: string | null): string {
  if (!dateString) return "";
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = date.getTime() - now.getTime();
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

  if (diffDays < 0) {
    return `${Math.abs(diffDays)} day${Math.abs(diffDays) !== 1 ? "s" : ""} overdue`;
  }
  if (diffDays === 0) {
    return "Due today";
  }
  if (diffDays === 1) {
    return "Due tomorrow";
  }
  return `Due in ${diffDays} days`;
}

function isDueOverdue(dateString: string | null): boolean {
  if (!dateString) return false;
  return new Date(dateString) < new Date();
}

interface ActionCardProps {
  action: VoiceAction;
  staffMembers: StaffMember[];
  onMarkComplete: (actionId: string) => void;
  onDismiss: (actionId: string) => void;
  onStartProgress: (actionId: string) => void;
  updating: string | null;
  isAdmin: boolean;
}

function ActionCard({
  action,
  staffMembers,
  onMarkComplete,
  onDismiss,
  onStartProgress,
  updating,
  isAdmin,
}: ActionCardProps) {
  const assignedStaff = action.assignedTo
    ? staffMembers.find((s) => s.id === action.assignedTo)
    : null;
  const isUpdating = updating === action.id;
  const overdue = isDueOverdue(action.dueAt);

  return (
    <div
      className={`border rounded-xl p-4 transition-all ${
        statusColors[action.status]
      } ${overdue && action.status === "PENDING" ? "ring-2 ring-red-300" : ""}`}
    >
      {/* Header */}
      <div className="flex items-start justify-between gap-3 mb-3">
        <div className="flex items-center gap-2">
          <span
            className={`p-1.5 rounded-lg ${typeColors[action.type] || "bg-gray-100 text-gray-700"}`}
          >
            {typeIcons[action.type] || <FileText className="w-4 h-4" />}
          </span>
          <div>
            <span className="text-xs font-medium uppercase tracking-wide opacity-75">
              {action.type.replace("_", " ")}
            </span>
          </div>
        </div>
        <span
          className={`px-2 py-0.5 rounded-full text-xs font-semibold uppercase ${
            action.status === "PENDING"
              ? "bg-yellow-200 text-yellow-900"
              : action.status === "IN_PROGRESS"
                ? "bg-blue-200 text-blue-900"
                : action.status === "COMPLETED"
                  ? "bg-green-200 text-green-900"
                  : "bg-gray-200 text-gray-700"
          }`}
        >
          {action.status.replace("_", " ")}
        </span>
      </div>

      {/* Title */}
      <h4 className="font-semibold text-gray-900 mb-2">{action.title}</h4>

      {/* Description */}
      {action.description && (
        <p className="text-sm text-gray-600 mb-3 line-clamp-2">
          {action.description}
        </p>
      )}

      {/* Meta */}
      <div className="flex flex-wrap gap-3 text-xs text-gray-500 mb-3">
        {action.dueAt && (
          <span
            className={`flex items-center gap-1 ${
              overdue && action.status !== "COMPLETED"
                ? "text-red-600 font-medium"
                : ""
            }`}
          >
            <Calendar className="w-3 h-3" />
            {formatDueDate(action.dueAt)}
          </span>
        )}
        {assignedStaff && (
          <span className="flex items-center gap-1">
            <User className="w-3 h-3" />
            {assignedStaff.name}
          </span>
        )}
        <span className="flex items-center gap-1">
          <Clock className="w-3 h-3" />
          {new Date(action.createdAt).toLocaleDateString()}
        </span>
      </div>

      {/* Actions */}
      {(action.status === "PENDING" || action.status === "IN_PROGRESS") && (
        <div className="flex flex-wrap gap-2 pt-2 border-t border-gray-200/50">
          {action.status === "PENDING" && (
            <button
              onClick={() => onStartProgress(action.id)}
              disabled={isUpdating}
              className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-blue-700 bg-blue-50 hover:bg-blue-100 rounded-lg transition disabled:opacity-50"
            >
              <Clock className="w-3.5 h-3.5" />
              Start
            </button>
          )}
          <button
            onClick={() => onMarkComplete(action.id)}
            disabled={isUpdating}
            className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-green-700 bg-green-50 hover:bg-green-100 rounded-lg transition disabled:opacity-50"
          >
            <CheckCircle className="w-3.5 h-3.5" />
            Complete
          </button>
          {isAdmin && (
            <button
              onClick={() => onDismiss(action.id)}
              disabled={isUpdating}
              className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-red-700 bg-red-50 hover:bg-red-100 rounded-lg transition disabled:opacity-50"
            >
              <XCircle className="w-3.5 h-3.5" />
              Dismiss
            </button>
          )}
        </div>
      )}
    </div>
  );
}

export default function NextActionsPanel({
  staffMembers,
  onActionUpdated,
}: NextActionsPanelProps) {
  const [actions, setActions] = useState<VoiceAction[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [updating, setUpdating] = useState<string | null>(null);
  const [toast, setToast] = useState<{
    message: string;
    type: "success" | "error";
  } | null>(null);

  // Filters
  const [statusFilter, setStatusFilter] = useState<VoiceActionStatus | "">("");
  const [assignedToFilter, setAssignedToFilter] = useState("");

  // Assume admin for now - in production, this would come from session
  const isAdmin = true;

  const fetchActions = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const params = new URLSearchParams();
      if (statusFilter) params.append("status", statusFilter);
      if (assignedToFilter) params.append("assignedTo", assignedToFilter);
      params.append("limit", "50");

      const response = await fetch(`/api/staff/voice-agents/actions?${params}`);

      if (!response.ok) {
        throw new Error("Failed to fetch actions");
      }

      const data = await response.json();
      setActions(data.actions);
      setTotal(data.total);
    } catch (err) {
      logger.error("Failed to fetch actions", { error: err });
      setError("Failed to load actions");
    } finally {
      setLoading(false);
    }
  }, [statusFilter, assignedToFilter]);

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

  // Auto-dismiss toast
  useEffect(() => {
    if (toast) {
      const timer = setTimeout(() => setToast(null), 5000);
      return () => clearTimeout(timer);
    }
  }, [toast]);

  const updateActionStatus = async (
    actionId: string,
    status: VoiceActionStatus,
  ) => {
    try {
      setUpdating(actionId);

      const response = await fetch(
        `/api/staff/voice-agents/actions/${actionId}`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ status }),
        },
      );

      if (!response.ok) {
        throw new Error("Failed to update action");
      }

      setToast({
        message: `Action marked as ${status.toLowerCase().replace("_", " ")}`,
        type: "success",
      });
      fetchActions();
      onActionUpdated();
    } catch (err) {
      logger.error("Failed to update action", { error: err, actionId, status });
      setToast({ message: "Failed to update action", type: "error" });
    } finally {
      setUpdating(null);
    }
  };

  const handleMarkComplete = (actionId: string) =>
    updateActionStatus(actionId, "COMPLETED");
  const handleDismiss = (actionId: string) =>
    updateActionStatus(actionId, "DISMISSED");
  const handleStartProgress = (actionId: string) =>
    updateActionStatus(actionId, "IN_PROGRESS");

  // Count pending/in-progress for header
  const pendingCount = actions.filter(
    (a) => a.status === "PENDING" || a.status === "IN_PROGRESS",
  ).length;

  // Loading state
  if (loading && actions.length === 0) {
    return (
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div className="p-4 border-b border-gray-200">
          <div className="h-6 bg-gray-200 rounded w-32 animate-pulse" />
        </div>
        <div className="p-4 space-y-3">
          {[...Array(3)].map((_, i) => (
            <div
              key={i}
              className="h-32 bg-gray-100 rounded-xl animate-pulse"
            />
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
      {/* Toast */}
      {toast && (
        <div
          className={`fixed top-4 right-4 z-50 px-4 py-3 rounded-lg shadow-lg ${
            toast.type === "success"
              ? "bg-green-50 border border-green-200 text-green-800"
              : "bg-red-50 border border-red-200 text-red-800"
          }`}
        >
          <div className="flex items-center gap-2">
            {toast.type === "success" ? (
              <CheckCircle className="w-4 h-4" />
            ) : (
              <AlertCircle className="w-4 h-4" />
            )}
            <span className="text-sm font-medium">{toast.message}</span>
          </div>
        </div>
      )}

      {/* Header */}
      <div className="p-4 border-b border-gray-200">
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
            <AlertCircle className="w-5 h-5 text-orange-500" />
            Next Actions
            {pendingCount > 0 && (
              <span className="px-2 py-0.5 text-xs font-bold bg-orange-100 text-orange-700 rounded-full">
                {pendingCount}
              </span>
            )}
          </h3>
          <button
            onClick={fetchActions}
            disabled={loading}
            className="text-sm text-blue-600 hover:text-blue-700 disabled:opacity-50"
          >
            Refresh
          </button>
        </div>

        {/* Filters */}
        <div className="flex flex-wrap gap-2">
          <div className="relative">
            <select
              value={statusFilter}
              onChange={(e) =>
                setStatusFilter(e.target.value as VoiceActionStatus | "")
              }
              className="appearance-none pl-3 pr-8 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"
            >
              <option value="">All Statuses</option>
              <option value="PENDING">Pending</option>
              <option value="IN_PROGRESS">In Progress</option>
              <option value="COMPLETED">Completed</option>
              <option value="DISMISSED">Dismissed</option>
            </select>
            <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
          </div>

          <div className="relative">
            <select
              value={assignedToFilter}
              onChange={(e) => setAssignedToFilter(e.target.value)}
              className="appearance-none pl-3 pr-8 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"
            >
              <option value="">All Staff</option>
              {staffMembers.map((staff) => (
                <option key={staff.id} value={staff.id}>
                  {staff.name}
                </option>
              ))}
            </select>
            <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
          </div>
        </div>
      </div>

      {/* Error State */}
      {error && (
        <div className="p-4 bg-red-50 border-b border-red-200">
          <div className="flex items-center gap-2 text-red-700">
            <AlertCircle className="w-4 h-4" />
            <span className="text-sm">{error}</span>
            <button
              onClick={fetchActions}
              className="ml-auto text-sm font-medium hover:underline"
            >
              Retry
            </button>
          </div>
        </div>
      )}

      {/* Actions List */}
      <div className="p-4 space-y-3 max-h-[600px] overflow-y-auto">
        {actions.length === 0 ? (
          <div className="text-center py-8">
            <CheckCircle className="w-12 h-12 text-green-300 mx-auto mb-3" />
            <h4 className="text-lg font-medium text-gray-900 mb-1">
              All Caught Up!
            </h4>
            <p className="text-gray-600">
              {statusFilter || assignedToFilter
                ? "No actions match your filters."
                : "No pending actions at the moment."}
            </p>
          </div>
        ) : (
          actions.map((action) => (
            <ActionCard
              key={action.id}
              action={action}
              staffMembers={staffMembers}
              onMarkComplete={handleMarkComplete}
              onDismiss={handleDismiss}
              onStartProgress={handleStartProgress}
              updating={updating}
              isAdmin={isAdmin}
            />
          ))
        )}
      </div>

      {/* Footer */}
      {total > 0 && (
        <div className="px-4 py-3 bg-gray-50 border-t border-gray-200">
          <p className="text-sm text-gray-600">
            Showing {actions.length} of {total} action{total !== 1 ? "s" : ""}
          </p>
        </div>
      )}
    </div>
  );
}
