"use client";

import { useState, useEffect } from "react";
import {
  Plug,
  CheckCircle,
  XCircle,
  AlertTriangle,
  Clock,
  RefreshCw,
  Search,
  Filter,
  ChevronLeft,
  ChevronRight,
  MessageCircle,
  Calendar,
  Zap,
  Link as LinkIcon,
} from "lucide-react";

interface IntegrationSummary {
  type: string;
  displayName: string;
  totalUsers: number;
  connectedCount: number;
  errorCount: number;
  disconnectedCount: number;
  pendingCount: number;
  lastError: string | null;
  lastErrorAt: string | null;
}

interface IntegrationUser {
  id: string;
  userId: string;
  type: string;
  status: "connected" | "disconnected" | "error" | "pending_setup";
  lastSyncAt: string | null;
  lastError: string | null;
  createdAt: string;
  updatedAt: string;
  user: {
    id: string;
    email: string;
    name: string | null;
    companyName: string | null;
  };
}

interface IntegrationError {
  id: string;
  type: string;
  lastError: string;
  updatedAt: string;
  user: {
    id: string;
    email: string;
    name: string | null;
  };
}

interface HealthStats {
  totalIntegrations: number;
  healthyCount: number;
  errorCount: number;
  disconnectedCount: number;
  healthPercentage: number;
  recentErrors: number;
}

const INTEGRATION_ICONS: Record<
  string,
  React.ComponentType<{ className?: string }>
> = {
  whatsapp: MessageCircle,
  google_calendar: Calendar,
  outlook_calendar: Calendar,
  salesforce: Zap,
  hubspot: Zap,
  zapier: Zap,
  make: LinkIcon,
};

export default function IntegrationsHealthDashboard() {
  const [summary, setSummary] = useState<IntegrationSummary[]>([]);
  const [stats, setStats] = useState<HealthStats | null>(null);
  const [users, setUsers] = useState<IntegrationUser[]>([]);
  const [errors, setErrors] = useState<IntegrationError[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingUsers, setLoadingUsers] = useState(false);
  const [selectedType, setSelectedType] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [total, setTotal] = useState(0);
  const [filters, setFilters] = useState({
    status: "",
    search: "",
  });
  const [viewMode, setViewMode] = useState<"grid" | "errors" | "users">("grid");

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

  useEffect(() => {
    if (selectedType) {
      fetchUsers();
    }
  }, [selectedType, page, filters]);

  const fetchData = async () => {
    setLoading(true);
    try {
      const [summaryRes, statsRes, errorsRes] = await Promise.all([
        fetch("/api/staff/dashboard/integrations?action=summary"),
        fetch("/api/staff/dashboard/integrations?action=stats"),
        fetch("/api/staff/dashboard/integrations?action=errors"),
      ]);

      if (summaryRes.ok) {
        const data = await summaryRes.json();
        setSummary(data.summary);
      }

      if (statsRes.ok) {
        const data = await statsRes.json();
        setStats(data);
      }

      if (errorsRes.ok) {
        const data = await errorsRes.json();
        setErrors(data.errors);
      }
    } catch (error) {
      console.error("Failed to fetch integration data:", error);
    } finally {
      setLoading(false);
    }
  };

  const fetchUsers = async () => {
    if (!selectedType) return;

    setLoadingUsers(true);
    try {
      const params = new URLSearchParams({
        type: selectedType,
        page: page.toString(),
        limit: "20",
      });

      if (filters.status) params.append("status", filters.status);
      if (filters.search) params.append("search", filters.search);

      const response = await fetch(
        `/api/staff/dashboard/integrations?${params}`,
      );
      if (response.ok) {
        const data = await response.json();
        setUsers(data.users);
        setTotalPages(data.totalPages);
        setTotal(data.total);
      }
    } catch (error) {
      console.error("Failed to fetch integration users:", error);
    } finally {
      setLoadingUsers(false);
    }
  };

  const getStatusBadge = (status: string) => {
    const configs: Record<
      string,
      {
        icon: React.ComponentType<{ className?: string }>;
        label: string;
        color: string;
      }
    > = {
      connected: {
        icon: CheckCircle,
        label: "Connected",
        color: "text-green-700 bg-green-50",
      },
      error: { icon: XCircle, label: "Error", color: "text-red-700 bg-red-50" },
      disconnected: {
        icon: AlertTriangle,
        label: "Disconnected",
        color: "text-gray-700 bg-gray-100",
      },
      pending_setup: {
        icon: Clock,
        label: "Pending",
        color: "text-yellow-700 bg-yellow-50",
      },
    };

    const config = configs[status] || configs.disconnected;
    const Icon = config.icon;

    return (
      <span
        className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${config.color}`}
      >
        <Icon className="w-3 h-3" />
        {config.label}
      </span>
    );
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <RefreshCw className="w-6 h-6 animate-spin text-gray-400" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Health Overview Stats */}
      {stats && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <StatCard
            label="Total Integrations"
            value={stats.totalIntegrations}
            icon={Plug}
            color="blue"
          />
          <StatCard
            label="Healthy"
            value={stats.healthyCount}
            icon={CheckCircle}
            color="green"
            subtitle={`${stats.healthPercentage}%`}
          />
          <StatCard
            label="Errors"
            value={stats.errorCount}
            icon={XCircle}
            color="red"
            highlight={stats.errorCount > 0}
          />
          <StatCard
            label="Disconnected"
            value={stats.disconnectedCount}
            icon={AlertTriangle}
            color="gray"
          />
        </div>
      )}

      {/* View Mode Tabs */}
      <div className="flex gap-2">
        <button
          onClick={() => {
            setViewMode("grid");
            setSelectedType(null);
          }}
          className={`px-4 py-2 text-sm font-medium rounded-lg transition ${
            viewMode === "grid"
              ? "bg-brand-green text-white"
              : "bg-gray-100 text-gray-700 hover:bg-gray-200"
          }`}
        >
          Integration Types
        </button>
        <button
          onClick={() => setViewMode("errors")}
          className={`px-4 py-2 text-sm font-medium rounded-lg transition ${
            viewMode === "errors"
              ? "bg-brand-green text-white"
              : "bg-gray-100 text-gray-700 hover:bg-gray-200"
          }`}
        >
          Error Log
          {errors.length > 0 && (
            <span className="ml-2 bg-red-500 text-white text-xs px-1.5 py-0.5 rounded-full">
              {errors.length}
            </span>
          )}
        </button>
      </div>

      {viewMode === "grid" && !selectedType && (
        /* Integration Types Grid */
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {summary.map((integration) => {
            const Icon = INTEGRATION_ICONS[integration.type] || Plug;
            const healthPercent =
              integration.totalUsers > 0
                ? Math.round(
                    (integration.connectedCount / integration.totalUsers) * 100,
                  )
                : 100;

            return (
              <div
                key={integration.type}
                onClick={() => {
                  setSelectedType(integration.type);
                  setViewMode("users");
                  setPage(1);
                }}
                className="bg-white border border-gray-200 rounded-xl p-5 hover:shadow-lg hover:border-brand-green/30 transition cursor-pointer"
              >
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-center gap-3">
                    <div className="w-12 h-12 bg-gray-100 rounded-xl flex items-center justify-center">
                      <Icon className="w-6 h-6 text-gray-600" />
                    </div>
                    <div>
                      <h3 className="font-semibold text-brand-ink">
                        {integration.displayName}
                      </h3>
                      <p className="text-sm text-gray-500">
                        {integration.totalUsers} users
                      </p>
                    </div>
                  </div>
                </div>

                {/* Stats */}
                <div className="grid grid-cols-2 gap-3 mb-4">
                  <div className="text-center p-2 bg-green-50 rounded-lg">
                    <p className="text-lg font-bold text-green-700">
                      {integration.connectedCount}
                    </p>
                    <p className="text-xs text-green-600">Connected</p>
                  </div>
                  <div className="text-center p-2 bg-red-50 rounded-lg">
                    <p className="text-lg font-bold text-red-700">
                      {integration.errorCount}
                    </p>
                    <p className="text-xs text-red-600">Errors</p>
                  </div>
                </div>

                {/* Health Bar */}
                <div>
                  <div className="flex justify-between text-xs text-gray-500 mb-1">
                    <span>Health</span>
                    <span>{healthPercent}%</span>
                  </div>
                  <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
                    <div
                      className={`h-full transition-all ${
                        healthPercent >= 80
                          ? "bg-green-500"
                          : healthPercent >= 50
                            ? "bg-yellow-500"
                            : "bg-red-500"
                      }`}
                      style={{ width: `${healthPercent}%` }}
                    />
                  </div>
                </div>

                {/* Last Error */}
                {integration.lastError && (
                  <div className="mt-3 p-2 bg-red-50 rounded-lg">
                    <p className="text-xs text-red-700 line-clamp-2">
                      {integration.lastError}
                    </p>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {viewMode === "users" && selectedType && (
        /* Users List for Selected Integration */
        <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
          <div className="p-4 border-b border-gray-200">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <button
                  onClick={() => {
                    setSelectedType(null);
                    setViewMode("grid");
                  }}
                  className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition"
                >
                  <ChevronLeft className="w-5 h-5" />
                </button>
                <div>
                  <h3 className="font-semibold text-brand-ink">
                    {summary.find((s) => s.type === selectedType)
                      ?.displayName || selectedType}
                  </h3>
                  <p className="text-sm text-gray-500">
                    {total} users with this integration
                  </p>
                </div>
              </div>

              {/* Filters */}
              <div className="flex items-center gap-3">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    type="text"
                    placeholder="Search users..."
                    value={filters.search}
                    onChange={(e) => {
                      setFilters({ ...filters, search: e.target.value });
                      setPage(1);
                    }}
                    className="pl-9 pr-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
                  />
                </div>
                <select
                  value={filters.status}
                  onChange={(e) => {
                    setFilters({ ...filters, status: e.target.value });
                    setPage(1);
                  }}
                  className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
                >
                  <option value="">All Status</option>
                  <option value="connected">Connected</option>
                  <option value="error">Error</option>
                  <option value="disconnected">Disconnected</option>
                  <option value="pending_setup">Pending</option>
                </select>
              </div>
            </div>
          </div>

          {/* Users Table */}
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="text-left text-xs font-medium text-gray-500 uppercase tracking-wider bg-gray-50">
                  <th className="px-6 py-3">User</th>
                  <th className="px-6 py-3">Status</th>
                  <th className="px-6 py-3">Last Sync</th>
                  <th className="px-6 py-3">Error</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {loadingUsers ? (
                  <tr>
                    <td
                      colSpan={4}
                      className="px-6 py-12 text-center text-gray-500"
                    >
                      <RefreshCw className="w-5 h-5 animate-spin mx-auto mb-2" />
                      Loading...
                    </td>
                  </tr>
                ) : users.length === 0 ? (
                  <tr>
                    <td
                      colSpan={4}
                      className="px-6 py-12 text-center text-gray-500"
                    >
                      No users found
                    </td>
                  </tr>
                ) : (
                  users.map((user) => (
                    <tr key={user.id} className="hover:bg-gray-50">
                      <td className="px-6 py-4">
                        <div>
                          <p className="font-medium text-brand-ink">
                            {user.user.name || "Unknown"}
                          </p>
                          <p className="text-sm text-gray-500">
                            {user.user.email}
                          </p>
                          {user.user.companyName && (
                            <p className="text-xs text-gray-400">
                              {user.user.companyName}
                            </p>
                          )}
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        {getStatusBadge(user.status)}
                      </td>
                      <td className="px-6 py-4">
                        {user.lastSyncAt ? (
                          <span className="text-sm text-gray-600">
                            {new Date(user.lastSyncAt).toLocaleString()}
                          </span>
                        ) : (
                          <span className="text-sm text-gray-400">Never</span>
                        )}
                      </td>
                      <td className="px-6 py-4">
                        {user.lastError ? (
                          <span className="text-sm text-red-600 line-clamp-2">
                            {user.lastError}
                          </span>
                        ) : (
                          <span className="text-sm text-gray-400">-</span>
                        )}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between px-6 py-4 border-t border-gray-200">
              <p className="text-sm text-gray-500">
                Page {page} of {totalPages}
              </p>
              <div className="flex gap-2">
                <button
                  onClick={() => setPage(page - 1)}
                  disabled={page === 1}
                  className="flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <ChevronLeft className="w-4 h-4" />
                  Previous
                </button>
                <button
                  onClick={() => setPage(page + 1)}
                  disabled={page === totalPages}
                  className="flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  Next
                  <ChevronRight className="w-4 h-4" />
                </button>
              </div>
            </div>
          )}
        </div>
      )}

      {viewMode === "errors" && (
        /* Error Log */
        <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
          <div className="p-4 border-b border-gray-200">
            <h3 className="font-semibold text-brand-ink">Integration Errors</h3>
            <p className="text-sm text-gray-500">
              {errors.length} integrations with errors
            </p>
          </div>

          {errors.length === 0 ? (
            <div className="p-12 text-center">
              <CheckCircle className="w-12 h-12 text-green-500 mx-auto mb-4" />
              <h4 className="font-semibold text-brand-ink mb-2">All Clear</h4>
              <p className="text-gray-500">No integration errors detected</p>
            </div>
          ) : (
            <div className="divide-y divide-gray-100">
              {errors.map((error) => {
                const Icon = INTEGRATION_ICONS[error.type] || Plug;
                return (
                  <div key={error.id} className="p-4 hover:bg-gray-50">
                    <div className="flex items-start gap-4">
                      <div className="w-10 h-10 bg-red-100 rounded-lg flex items-center justify-center shrink-0">
                        <Icon className="w-5 h-5 text-red-600" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-start justify-between">
                          <div>
                            <p className="font-medium text-brand-ink">
                              {error.user.name || error.user.email}
                            </p>
                            <p className="text-sm text-gray-500">
                              {error.user.email}
                            </p>
                          </div>
                          <span className="text-xs text-gray-400">
                            {new Date(error.updatedAt).toLocaleString()}
                          </span>
                        </div>
                        <div className="mt-2 p-3 bg-red-50 rounded-lg">
                          <p className="text-sm text-red-700">
                            {error.lastError}
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function StatCard({
  label,
  value,
  icon: Icon,
  color,
  subtitle,
  highlight,
}: {
  label: string;
  value: number;
  icon: React.ComponentType<{ className?: string }>;
  color: "blue" | "green" | "red" | "gray";
  subtitle?: string;
  highlight?: boolean;
}) {
  const colors = {
    blue: "bg-blue-50 text-blue-600",
    green: "bg-green-50 text-green-600",
    red: "bg-red-50 text-red-600",
    gray: "bg-gray-50 text-gray-600",
  };

  return (
    <div
      className={`bg-white rounded-xl border p-4 ${
        highlight ? "border-red-300 ring-2 ring-red-100" : "border-gray-200"
      }`}
    >
      <div className="flex items-center gap-3">
        <div className={`p-2.5 rounded-lg ${colors[color]}`}>
          <Icon className="w-5 h-5" />
        </div>
        <div>
          <p className="text-2xl font-bold text-brand-ink">
            {value}
            {subtitle && (
              <span className="text-sm font-normal text-gray-500 ml-1">
                {subtitle}
              </span>
            )}
          </p>
          <p className="text-xs text-gray-500">{label}</p>
        </div>
      </div>
    </div>
  );
}
