"use client";

import Link from "next/link";
import { useMemo, useState } from "react";
import { Bot, Receipt } from "lucide-react";
import { countDigitalRoles, getAllAutomatableRoles } from "@/lib/role-automation/task-catalog";
import { personalizeTasksForRole } from "@/lib/role-automation/task-preview";
import { ROLE_GROUP_LABELS } from "@/lib/role-intelligence";
import { AI_LEADER_ROLE_NAME, resolveUserRole } from "@/lib/user-workplace-role";
import { AiLeaderCard } from "@/components/roles/ai-leader-card";
import { RoleTaskList } from "@/components/roles/task-box";
import { AutomationPlatformOverview } from "@/components/roles/automation-flow-panel";
import { getTaskAutomationFlow } from "@/lib/role-automation/automation-flow";
import { AutomationFlowSteps } from "@/components/roles/automation-flow-panel";
import type { Business, RoleAutomationRun } from "@/lib/types";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  CheckCircle2,
  ChevronDown,
  ChevronUp,
  ClipboardCopy,
} from "lucide-react";

interface RoleAgentsPanelProps {
  business: Business;
  onUpdate: (business: Business) => void;
  initialRole?: string;
}

function formatTime(iso: string) {
  return new Date(iso).toLocaleString(undefined, {
    month: "short",
    day: "numeric",
    hour: "numeric",
    minute: "2-digit",
  });
}

function ReceiptCard({ receipt }: { receipt: RoleAutomationRun["receipts"][0] }) {
  const [expanded, setExpanded] = useState(false);
  const [copied, setCopied] = useState(false);

  const copyArtifact = async () => {
    await navigator.clipboard.writeText(receipt.artifact);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="rounded-xl border border-slate-800 bg-slate-900/40 p-4">
      <div className="flex flex-wrap items-start justify-between gap-2">
        <div className="flex items-start gap-2">
          <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0 text-emerald-400" />
          <div>
            <p className="font-medium text-slate-100">{receipt.taskTitle}</p>
            <p className="mt-1 text-sm text-slate-400">{receipt.summary}</p>
            <p className="mt-1 text-xs text-slate-500">{receipt.integrationTarget}</p>
          </div>
        </div>
        <Badge className="border-emerald-500/30 bg-emerald-500/10 text-emerald-200">{receipt.status}</Badge>
      </div>

      {receipt.metrics ? (
        <div className="mt-3 flex flex-wrap gap-2">
          {Object.entries(receipt.metrics).map(([key, value]) => (
            <span key={key} className="rounded-md border border-slate-700 px-2 py-0.5 text-xs text-slate-400">
              {key}: {value}
            </span>
          ))}
        </div>
      ) : null}

      <div className="mt-3 flex flex-wrap gap-2">
        <Button variant="outline" size="sm" className="gap-1.5" onClick={() => setExpanded((v) => !v)}>
          {expanded ? <ChevronUp className="h-3.5 w-3.5" /> : <ChevronDown className="h-3.5 w-3.5" />}
          {expanded ? "Hide receipt" : "View receipt"}
        </Button>
        <Button variant="outline" size="sm" className="gap-1.5" onClick={copyArtifact}>
          <ClipboardCopy className="h-3.5 w-3.5" />
          {copied ? "Copied" : "Copy deliverable"}
        </Button>
      </div>

      {expanded ? (
        <pre className="mt-3 max-h-64 overflow-auto whitespace-pre-wrap rounded-lg border border-slate-800 bg-slate-950 p-3 text-xs text-slate-300">
          {receipt.artifact}
        </pre>
      ) : null}
    </div>
  );
}

function RunReport({ run, business }: { run: RoleAutomationRun; business: Business }) {
  return (
    <Card className="border-emerald-500/20 bg-emerald-500/5">
      <CardHeader>
        <CardTitle className="flex flex-wrap items-center gap-2 text-base">
          <Receipt className="h-4 w-4 text-emerald-400" />
          {run.roleName} — {run.tasksTotal === 1 ? "task complete" : "execution report"}
          <Badge className="border-emerald-500/30 bg-emerald-500/10 text-emerald-200">
            {run.tasksCompleted}/{run.tasksTotal} tasks
          </Badge>
        </CardTitle>
        <p className="text-xs text-slate-500">{formatTime(run.completedAt)}</p>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="rounded-xl border border-slate-800 bg-slate-950/50 p-4 text-sm text-slate-300">
          <p className="text-xs uppercase text-slate-500">Summary</p>
          <p className="mt-2">{run.executiveSummary}</p>
          {run.estimatedRevenueImpact ? (
            <p className="mt-2 text-amber-300">
              Revenue impact focus: ${run.estimatedRevenueImpact.toLocaleString()}
            </p>
          ) : null}
        </div>

        <div className="space-y-3">
          <p className="text-xs uppercase text-slate-500">Receipts</p>
          {run.receipts.map((receipt) => (
            <div key={`${run.id}-${receipt.taskId}`} className="space-y-2">
              <ReceiptCard receipt={receipt} />
              <div className="rounded-lg border border-violet-500/10 bg-violet-500/5 p-3">
                <p className="mb-2 text-[10px] font-medium uppercase tracking-wide text-violet-300">
                  Automation completed
                </p>
                <AutomationFlowSteps
                  flow={getTaskAutomationFlow(
                    receipt.taskId,
                    business,
                    run.roleName,
                    receipt.integrationTarget,
                  )}
                  size="sm"
                />
              </div>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  );
}

export function RoleAgentsPanel({ business, onUpdate, initialRole }: RoleAgentsPanelProps) {
  const roles = business.roleIntelligence;
  const [latestRun, setLatestRun] = useState<RoleAutomationRun | null>(null);
  const [expandedRole, setExpandedRole] = useState<string | null>(initialRole ?? null);

  const automatableRoles = useMemo(() => {
    if (!roles) return [];
    return getAllAutomatableRoles(roles.roleGroups);
  }, [roles]);

  const pastRuns = business.roleAutomationRuns ?? [];
  const userRole = resolveUserRole(business);

  const personalizedByRole = useMemo(() => {
    const map = new Map<string, ReturnType<typeof personalizeTasksForRole>>();
    for (const { role } of automatableRoles) {
      map.set(role, personalizeTasksForRole(business, role));
    }
    if (userRole.aiLeaderEnabled) {
      map.set(AI_LEADER_ROLE_NAME, personalizeTasksForRole(business, AI_LEADER_ROLE_NAME));
    }
    return map;
  }, [automatableRoles, business, userRole.aiLeaderEnabled]);

  if (!roles) {
    return (
      <Card>
        <CardContent className="p-6 text-sm text-slate-400">
          Team blueprint is loading. Reload a demo from Settings if this persists.
          <div className="mt-4">
            <Link href="/demo">
              <Button size="sm">Reload demo</Button>
            </Link>
          </div>
        </CardContent>
      </Card>
    );
  }

  const toggleRole = (role: string) => {
    setExpandedRole((current) => (current === role ? null : role));
  };

  return (
    <div className="space-y-6">
      <Card className="border-sky-500/20 bg-gradient-to-br from-sky-500/10 to-slate-950">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Bot className="h-5 w-5 text-sky-400" />
            Role Agents
          </CardTitle>
        </CardHeader>
        <CardContent className="text-sm text-slate-300">
          Only <strong className="text-slate-100">digital roles</strong> appear here — marketing, CRM, scheduling desk work, compliance docs, and similar tasks BrandLxft can actually execute online.
          {roles ? (
            <span className="mt-1 block text-xs text-slate-500">
              {countDigitalRoles(roles.roleGroups).automatable} digital agents · {countDigitalRoles(roles.roleGroups).manual} manual/field roles in your blueprint (not automatable)
            </span>
          ) : null}
        </CardContent>
      </Card>

      {latestRun ? <RunReport run={latestRun} business={business} /> : null}

      <AutomationPlatformOverview />

      <AiLeaderCard
        business={business}
        onUpdate={onUpdate}
        variant="full"
        onRunComplete={setLatestRun}
      />

      {userRole.aiLeaderEnabled ? (
        <Card className={expandedRole === AI_LEADER_ROLE_NAME ? "border-amber-500/40 ring-1 ring-amber-500/20" : "border-amber-500/20"}>
          <CardHeader className="pb-2">
            <button
              type="button"
              className="w-full text-left"
              onClick={() => toggleRole(AI_LEADER_ROLE_NAME)}
            >
              <CardTitle className="text-sm font-medium">{AI_LEADER_ROLE_NAME}</CardTitle>
              <p className="text-xs text-slate-500">{ROLE_GROUP_LABELS.leadership} · {personalizedByRole.get(AI_LEADER_ROLE_NAME)?.length ?? 0} tasks</p>
            </button>
          </CardHeader>
          {(expandedRole === AI_LEADER_ROLE_NAME || initialRole === AI_LEADER_ROLE_NAME) && (
            <CardContent>
              <RoleTaskList
                roleName={AI_LEADER_ROLE_NAME}
                roleGroup="leadership"
                tasks={personalizedByRole.get(AI_LEADER_ROLE_NAME) ?? []}
                business={business}
                pastRuns={pastRuns}
                onRunComplete={setLatestRun}
                onBusinessUpdate={onUpdate}
              />
            </CardContent>
          )}
        </Card>
      ) : null}

      <div className="space-y-3">
        {automatableRoles.map(({ role, group }) => {
          const tasks = personalizedByRole.get(role) ?? [];
          const isExpanded = expandedRole === role;
          const isHighlighted = initialRole === role;

          return (
            <Card
              key={`${group}-${role}`}
              className={isHighlighted || isExpanded ? "border-sky-500/40 ring-1 ring-sky-500/20" : undefined}
            >
              <CardHeader className="pb-2">
                <button type="button" className="w-full text-left" onClick={() => toggleRole(role)}>
                  <CardTitle className="text-sm font-medium">{role}</CardTitle>
                  <p className="text-xs text-slate-500">
                    {ROLE_GROUP_LABELS[group]} · {tasks.length} personalized tasks
                  </p>
                </button>
              </CardHeader>
              {isExpanded ? (
                <CardContent>
                  <RoleTaskList
                    roleName={role}
                    roleGroup={group}
                    tasks={tasks}
                    business={business}
                    pastRuns={pastRuns}
                    onRunComplete={setLatestRun}
                    onBusinessUpdate={onUpdate}
                  />
                </CardContent>
              ) : (
                <CardContent className="pt-0">
                  <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
                    {tasks.map((task) => (
                      <div
                        key={task.id}
                        className="rounded-lg border border-slate-800/80 bg-slate-900/30 px-3 py-2 text-xs text-slate-400"
                      >
                        <p className="font-medium text-slate-300">{task.title}</p>
                        <p className="mt-0.5 line-clamp-2 text-sky-200/70">{task.personalizedPreview}</p>
                      </div>
                    ))}
                  </div>
                  <Button variant="outline" size="sm" className="mt-3 w-full" onClick={() => toggleRole(role)}>
                    Show tasks & run
                  </Button>
                </CardContent>
              )}
            </Card>
          );
        })}
      </div>

      {pastRuns.length > 0 ? (
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Run history</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {pastRuns.slice(0, 10).map((run) => (
              <div key={run.id} className="rounded-xl border border-slate-800 p-4">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <div>
                    <p className="font-medium">{run.roleName}</p>
                    <p className="text-xs text-slate-500">
                      {run.receipts.map((r) => r.taskTitle).join(" · ")} · {formatTime(run.completedAt)}
                    </p>
                  </div>
                  <Badge className="border-slate-700 bg-slate-800/50 text-slate-300">
                    {run.tasksCompleted} receipt{run.tasksCompleted !== 1 ? "s" : ""}
                  </Badge>
                </div>
                <Button variant="outline" size="sm" className="mt-3" onClick={() => setLatestRun(run)}>
                  View report
                </Button>
              </div>
            ))}
          </CardContent>
        </Card>
      ) : null}
    </div>
  );
}
