"use client";

import Link from "next/link";
import { useBrand, type SourceStatusEntry } from "@/context/brand-context";
import { AlertCircle, Loader2, Clock, Plug, Database, ArrowRight, CheckCircle2, AlertTriangle, PlayCircle } from "lucide-react";

const STATUS_CONFIG: Record<string, { icon: typeof AlertCircle; color: string; bg: string; border: string; animate?: boolean }> = {
  not_connected:       { icon: Plug,           color: "text-slate-400",  bg: "bg-slate-50",  border: "border-slate-200" },
  no_data:             { icon: Database,       color: "text-slate-400",  bg: "bg-slate-50",  border: "border-slate-200" },
  queued:              { icon: Clock,          color: "text-blue-500",   bg: "bg-blue-50",   border: "border-blue-200" },
  running:             { icon: Loader2,        color: "text-blue-500",   bg: "bg-blue-50",   border: "border-blue-200", animate: true },
  completed:           { icon: CheckCircle2,   color: "text-green-500",  bg: "bg-green-50",  border: "border-green-200" },
  stale:               { icon: Clock,          color: "text-amber-500",  bg: "bg-amber-50",  border: "border-amber-200" },
  failed:              { icon: AlertCircle,    color: "text-red-500",    bg: "bg-red-50",    border: "border-red-200" },
  partial_failure:     { icon: AlertTriangle,  color: "text-amber-500",  bg: "bg-amber-50",  border: "border-amber-200" },
  partially_available: { icon: Database,       color: "text-amber-500",  bg: "bg-amber-50",  border: "border-amber-200" },
  awaiting_first_run:  { icon: PlayCircle,     color: "text-blue-400",   bg: "bg-blue-50",   border: "border-blue-200" },
};

const STATUS_MESSAGES: Record<string, { title: string; description: string }> = {
  not_connected: {
    title: "Not Connected",
    description: "This data source is not set up yet. Connect it to start seeing real data.",
  },
  no_data: {
    title: "No Data Yet",
    description: "This source is set up but hasn't collected any data yet.",
  },
  queued: {
    title: "Queued",
    description: "A run has been scheduled and will start shortly.",
  },
  running: {
    title: "Running",
    description: "Data is being collected. Results will appear when complete.",
  },
  completed: {
    title: "Completed",
    description: "Data collection finished successfully.",
  },
  stale: {
    title: "Data May Be Outdated",
    description: "The last data collection was more than 30 days ago. Re-run to get fresh results.",
  },
  failed: {
    title: "Last Run Failed",
    description: "The most recent data collection encountered an error. Try again.",
  },
  partial_failure: {
    title: "Partial Failure",
    description: "Some data was collected but part of the run failed. Review results and retry.",
  },
  partially_available: {
    title: "Partially Available",
    description: "Some data exists but the source is not fully configured.",
  },
  awaiting_first_run: {
    title: "Ready to Run",
    description: "This source is set up and ready. Run it for the first time to start collecting data.",
  },
};

/** States where the source has usable data */
const DATA_AVAILABLE_STATES = new Set(["connected", "completed", "stale", "partial_failure", "partially_available"]);

/** Check if a source status represents usable data */
export function hasData(status: string | undefined): boolean {
  return !!status && DATA_AVAILABLE_STATES.has(status);
}

interface SourceEmptyStateProps {
  sourceId: string;
  title: string;
  description?: string;
  actionLabel?: string;
  actionHref?: string;
}

export function SourceEmptyState({ sourceId, title, description, actionLabel, actionHref }: SourceEmptyStateProps) {
  const { getSourceStatus } = useBrand();
  const source = getSourceStatus(sourceId);

  const status = source?.status ?? "no_data";
  const cfg = STATUS_CONFIG[status] ?? STATUS_CONFIG.no_data;
  const msg = STATUS_MESSAGES[status] ?? STATUS_MESSAGES.no_data;
  const Icon = cfg.icon;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-slate-900">{title}</h1>
        <p className="text-slate-500 text-sm mt-1">{description ?? msg.description}</p>
      </div>
      <div className={`rounded-xl border ${cfg.border} ${cfg.bg} p-8 text-center`}>
        <Icon className={`w-12 h-12 mx-auto mb-3 ${cfg.color} ${cfg.animate ? "animate-spin" : ""}`} />
        <h2 className="text-lg font-bold text-slate-900 mb-1">{msg.title}</h2>
        <p className="text-sm text-slate-500 max-w-md mx-auto mb-1">
          {source?.detail ?? msg.description}
        </p>
        {source?.lastUpdated && (
          <p className="text-xs text-slate-400 mt-2">
            Last updated: {new Date(source.lastUpdated).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
          </p>
        )}
        {actionLabel && actionHref && !cfg.animate && (
          <Link
            href={actionHref}
            className="inline-flex items-center gap-1.5 mt-4 px-5 py-2.5 bg-brand-600 text-white text-sm font-semibold rounded-xl hover:bg-brand-700 transition-colors"
          >
            {actionLabel}
            <ArrowRight className="w-3.5 h-3.5" />
          </Link>
        )}
      </div>
    </div>
  );
}
