"use client";

import { useState, useEffect } from "react";
import {
  AlertTriangle,
  Clock,
  CheckCircle,
  Phone,
  Mail,
  FileText,
  ExternalLink,
  RefreshCw,
  AlertCircle,
} from "lucide-react";

// SLA types
type SLAType = "demo_followup" | "contact_reply" | "proposal";

// SLA item interface
interface SLAItem {
  id: string;
  type: SLAType;
  title: string;
  description: string;
  dueAt: string;
  overdueByMs: number;
  status: "overdue" | "at_risk" | "on_track";
  assignee?: string;
  actionUrl: string;
  createdAt: string;
  email?: string;
}

// SLA compliance stats
interface SLACompliance {
  type: SLAType;
  label: string;
  total: number;
  onTime: number;
  overdue: number;
  complianceRate: number;
}

// Full SLA response
interface SLAResponse {
  overdueItems: SLAItem[];
  atRiskItems: SLAItem[];
  compliance: SLACompliance[];
  summary: {
    totalOverdue: number;
    totalAtRisk: number;
    overallCompliance: number;
  };
}

// Format time remaining/overdue
function formatTimeDiff(ms: number): string {
  const absMs = Math.abs(ms);
  const hours = Math.floor(absMs / (1000 * 60 * 60));
  const minutes = Math.floor((absMs % (1000 * 60 * 60)) / (1000 * 60));

  if (hours > 24) {
    const days = Math.floor(hours / 24);
    return `${days}d ${hours % 24}h`;
  }
  if (hours > 0) {
    return `${hours}h ${minutes}m`;
  }
  return `${minutes}m`;
}

// Get icon for SLA type
function SLATypeIcon({ type }: { type: SLAType }) {
  switch (type) {
    case "demo_followup":
      return <Phone className="h-4 w-4" />;
    case "contact_reply":
      return <Mail className="h-4 w-4" />;
    case "proposal":
      return <FileText className="h-4 w-4" />;
    default:
      return <Clock className="h-4 w-4" />;
  }
}

// Compliance badge component
function ComplianceBadge({ rate }: { rate: number }) {
  let colorClass = "bg-green-100 text-green-800";
  if (rate < 70) {
    colorClass = "bg-red-100 text-red-800";
  } else if (rate < 90) {
    colorClass = "bg-yellow-100 text-yellow-800";
  }

  return (
    <span
      className={`px-2 py-1 rounded-full text-xs font-medium ${colorClass}`}
    >
      {rate}%
    </span>
  );
}

// SLA Item Card
function SLAItemCard({ item }: { item: SLAItem }) {
  const isOverdue = item.status === "overdue";
  const isAtRisk = item.status === "at_risk";

  const borderColor = isOverdue
    ? "border-l-red-500"
    : isAtRisk
      ? "border-l-yellow-500"
      : "border-l-green-500";

  const bgColor = isOverdue
    ? "bg-red-50"
    : isAtRisk
      ? "bg-yellow-50"
      : "bg-white";

  return (
    <div className={`border-l-4 ${borderColor} ${bgColor} rounded-r p-3 mb-2`}>
      <div className="flex items-start justify-between">
        <div className="flex items-start gap-2">
          <div
            className={`mt-0.5 ${isOverdue ? "text-red-500" : isAtRisk ? "text-yellow-500" : "text-gray-500"}`}
          >
            <SLATypeIcon type={item.type} />
          </div>
          <div>
            <h4 className="text-sm font-medium text-gray-900">{item.title}</h4>
            <p className="text-xs text-gray-500">{item.description}</p>
            {item.email && (
              <p className="text-xs text-gray-400 mt-1">{item.email}</p>
            )}
          </div>
        </div>
        <div className="text-right">
          <div
            className={`text-sm font-medium ${isOverdue ? "text-red-600" : isAtRisk ? "text-yellow-600" : "text-green-600"}`}
          >
            {isOverdue
              ? `${formatTimeDiff(item.overdueByMs)} overdue`
              : `${formatTimeDiff(item.overdueByMs)} left`}
          </div>
          <a
            href={item.actionUrl}
            className="text-xs text-blue-600 hover:text-blue-800 flex items-center gap-1 justify-end mt-1"
          >
            Take action <ExternalLink className="h-3 w-3" />
          </a>
        </div>
      </div>
    </div>
  );
}

// Loading skeleton
function LoadingSkeleton() {
  return (
    <div className="animate-pulse space-y-4">
      <div className="grid grid-cols-3 gap-4">
        <div className="h-20 bg-gray-200 rounded" />
        <div className="h-20 bg-gray-200 rounded" />
        <div className="h-20 bg-gray-200 rounded" />
      </div>
      <div className="space-y-2">
        <div className="h-16 bg-gray-200 rounded" />
        <div className="h-16 bg-gray-200 rounded" />
        <div className="h-16 bg-gray-200 rounded" />
      </div>
    </div>
  );
}

export function SLAPanel() {
  const [data, setData] = useState<SLAResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [filter, setFilter] = useState<SLAType | "all">("all");

  const fetchData = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch("/api/staff/analytics/sla", {
        credentials: "include",
      });

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

      const result = await response.json();
      setData(result);
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setLoading(false);
    }
  };

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

  if (loading) {
    return (
      <div className="bg-white rounded-lg shadow p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">
          SLA Performance
        </h3>
        <LoadingSkeleton />
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-white rounded-lg shadow p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">
          SLA Performance
        </h3>
        <div className="text-center py-8 text-gray-500">
          <AlertCircle className="h-8 w-8 mx-auto mb-2 text-red-500" />
          <p>Failed to load SLA data</p>
          <p className="text-sm">{error}</p>
        </div>
      </div>
    );
  }

  if (!data) return null;

  // Filter items
  const filteredOverdue =
    filter === "all"
      ? data.overdueItems
      : data.overdueItems.filter((item) => item.type === filter);

  const filteredAtRisk =
    filter === "all"
      ? data.atRiskItems
      : data.atRiskItems.filter((item) => item.type === filter);

  return (
    <div className="bg-white rounded-lg shadow p-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <h3 className="text-lg font-semibold text-gray-900">
            SLA Performance
          </h3>
          {data.summary.totalOverdue > 0 && (
            <span className="px-2 py-0.5 bg-red-100 text-red-800 rounded-full text-xs font-medium">
              {data.summary.totalOverdue} overdue
            </span>
          )}
        </div>
        <div className="flex items-center gap-2">
          <select
            value={filter}
            onChange={(e) => setFilter(e.target.value as SLAType | "all")}
            className="px-2 py-1 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="all">All Types</option>
            <option value="demo_followup">Demo Follow-up</option>
            <option value="contact_reply">Contact Reply</option>
            <option value="proposal">Proposal</option>
          </select>
          <button
            onClick={fetchData}
            className="p-1.5 text-gray-500 hover:text-gray-700 rounded-md hover:bg-gray-100"
            title="Refresh"
          >
            <RefreshCw className="h-4 w-4" />
          </button>
        </div>
      </div>

      {/* Compliance Grid */}
      <div className="grid grid-cols-3 gap-4 mb-6">
        {data.compliance.map((item) => (
          <div
            key={item.type}
            className="p-4 bg-gray-50 rounded-lg border border-gray-200"
          >
            <div className="flex items-center justify-between mb-2">
              <span className="text-xs font-medium text-gray-500">
                {item.label}
              </span>
              <ComplianceBadge rate={item.complianceRate} />
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle className="h-4 w-4 text-green-500" />
              <span className="text-sm text-gray-600">
                {item.onTime} on-time
              </span>
            </div>
            {item.overdue > 0 && (
              <div className="flex items-center gap-2 mt-1">
                <AlertTriangle className="h-4 w-4 text-red-500" />
                <span className="text-sm text-red-600">
                  {item.overdue} overdue
                </span>
              </div>
            )}
          </div>
        ))}
      </div>

      {/* Overall Compliance */}
      <div className="flex items-center justify-between p-3 bg-gray-100 rounded-lg mb-6">
        <span className="text-sm font-medium text-gray-700">
          Overall SLA Compliance
        </span>
        <div className="flex items-center gap-2">
          <div className="w-32 h-2 bg-gray-300 rounded-full overflow-hidden">
            <div
              className={`h-full rounded-full ${
                data.summary.overallCompliance >= 90
                  ? "bg-green-500"
                  : data.summary.overallCompliance >= 70
                    ? "bg-yellow-500"
                    : "bg-red-500"
              }`}
              style={{ width: `${data.summary.overallCompliance}%` }}
            />
          </div>
          <span className="text-sm font-bold">
            {data.summary.overallCompliance}%
          </span>
        </div>
      </div>

      {/* Overdue Items */}
      {filteredOverdue.length > 0 && (
        <div className="mb-6">
          <h4 className="text-sm font-semibold text-red-700 mb-2 flex items-center gap-2">
            <AlertTriangle className="h-4 w-4" />
            Overdue ({filteredOverdue.length})
          </h4>
          <div className="max-h-64 overflow-y-auto">
            {filteredOverdue.map((item) => (
              <SLAItemCard key={item.id} item={item} />
            ))}
          </div>
        </div>
      )}

      {/* At Risk Items */}
      {filteredAtRisk.length > 0 && (
        <div>
          <h4 className="text-sm font-semibold text-yellow-700 mb-2 flex items-center gap-2">
            <Clock className="h-4 w-4" />
            At Risk ({filteredAtRisk.length})
          </h4>
          <div className="max-h-64 overflow-y-auto">
            {filteredAtRisk.map((item) => (
              <SLAItemCard key={item.id} item={item} />
            ))}
          </div>
        </div>
      )}

      {/* No Items Message */}
      {filteredOverdue.length === 0 && filteredAtRisk.length === 0 && (
        <div className="text-center py-8 text-gray-500">
          <CheckCircle className="h-12 w-12 mx-auto mb-2 text-green-500" />
          <p className="font-medium">All SLAs on track!</p>
          <p className="text-sm">No overdue or at-risk items</p>
        </div>
      )}
    </div>
  );
}

export default SLAPanel;
