"use client";

import { useState } from "react";
import { CheckCircle2, Clock, Loader2, Play } from "lucide-react";
import { saveBusiness } from "@/lib/data-store";
import { AutomationFlowPanel } from "@/components/roles/automation-flow-panel";
import type { Business, PersonalizedRoleTask, RoleAutomationRun, RoleGroups, RoleTaskReceipt } from "@/lib/types";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";

interface TaskBoxProps {
  task: PersonalizedRoleTask;
  roleName: string;
  roleGroup?: keyof RoleGroups;
  business: Business;
  disabled?: boolean;
  onRunningChange?: (running: boolean) => void;
  lastReceipt?: RoleTaskReceipt;
  onRunComplete?: (run: RoleAutomationRun) => void;
  onBusinessUpdate?: (business: Business) => void;
}

export function TaskBox({
  task,
  roleName,
  roleGroup,
  business,
  disabled,
  onRunningChange,
  lastReceipt,
  onRunComplete,
  onBusinessUpdate,
}: TaskBoxProps) {
  const [running, setRunning] = useState(false);
  const completed = !!lastReceipt;

  const runTask = async () => {
    setRunning(true);
    onRunningChange?.(true);
    try {
      const res = await fetch("/api/roles/automate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          business,
          roleName,
          roleGroup,
          taskId: task.id,
        }),
      });
      if (!res.ok) throw new Error("Failed");
      const { run } = (await res.json()) as { run: RoleAutomationRun };
      const next: Business = {
        ...business,
        roleAutomationRuns: [run, ...(business.roleAutomationRuns ?? [])].slice(0, 50),
        updatedAt: new Date().toISOString(),
      };
      onBusinessUpdate?.(next);
      onRunComplete?.(run);
      await saveBusiness(next);
    } finally {
      setRunning(false);
      onRunningChange?.(false);
    }
  };

  return (
    <div
      className={`rounded-xl border p-3 transition ${
        completed
          ? "border-emerald-500/30 bg-emerald-500/5"
          : "border-slate-800 bg-slate-900/50 hover:border-sky-500/30"
      }`}
    >
      <div className="flex items-start justify-between gap-2">
        <p className="text-sm font-medium text-slate-100">{task.title}</p>
        {completed ? (
          <CheckCircle2 className="h-4 w-4 shrink-0 text-emerald-400" aria-label="Completed" />
        ) : null}
      </div>

      <p className="mt-1.5 text-xs leading-relaxed text-sky-200/90">{task.personalizedPreview}</p>
      <p className="mt-1 text-xs text-slate-500">{task.description}</p>

      <div className="mt-2 flex flex-wrap gap-1">
        {task.contextTags.slice(0, 3).map((tag) => (
          <Badge key={tag} className="border-slate-700 bg-slate-800/60 text-[10px] text-slate-400">
            {tag}
          </Badge>
        ))}
        <span className="inline-flex items-center gap-0.5 text-[10px] text-slate-500">
          <Clock className="h-3 w-3" />
          {task.estimatedMinutes}m
        </span>
      </div>

      <AutomationFlowPanel
        taskId={task.id}
        roleName={roleName}
        integrationTarget={task.integrationTarget}
        business={business}
        compact
      />

      {lastReceipt ? (
        <p className="mt-2 text-xs text-emerald-300/90 line-clamp-2">{lastReceipt.summary}</p>
      ) : null}

      <Button
        size="sm"
        variant={completed ? "outline" : "default"}
        className="mt-3 w-full gap-1.5"
        disabled={disabled || running}
        onClick={runTask}
      >
        {running ? (
          <>
            <Loader2 className="h-3.5 w-3.5 animate-spin" />
            Running…
          </>
        ) : (
          <>
            <Play className="h-3.5 w-3.5" />
            {completed ? "Run again" : "Run task"}
          </>
        )}
      </Button>
    </div>
  );
}

interface RoleTaskListProps {
  roleName: string;
  roleGroup?: keyof RoleGroups;
  tasks: PersonalizedRoleTask[];
  business: Business;
  pastRuns?: RoleAutomationRun[];
  onRunComplete?: (run: RoleAutomationRun) => void;
  onBusinessUpdate?: (business: Business) => void;
  showRunAll?: boolean;
}

export function RoleTaskList({
  roleName,
  roleGroup,
  tasks,
  business,
  pastRuns = [],
  onRunComplete,
  onBusinessUpdate,
  showRunAll = true,
}: RoleTaskListProps) {
  const [runningAll, setRunningAll] = useState(false);
  const [runningTaskId, setRunningTaskId] = useState<string | null>(null);
  const roleRuns = pastRuns.filter((r) => r.roleName === roleName);
  const anyRunning = runningAll || !!runningTaskId;

  const lastReceiptForTask = (taskId: string) => {
    for (const run of roleRuns) {
      const receipt = run.receipts.find((r) => r.taskId === taskId);
      if (receipt) return receipt;
    }
    return undefined;
  };

  const runAll = async () => {
    setRunningAll(true);
    try {
      const res = await fetch("/api/roles/automate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ business, roleName, roleGroup }),
      });
      if (!res.ok) throw new Error("Failed");
      const { run } = (await res.json()) as { run: RoleAutomationRun };
      const next: Business = {
        ...business,
        roleAutomationRuns: [run, ...(business.roleAutomationRuns ?? [])].slice(0, 50),
        updatedAt: new Date().toISOString(),
      };
      onBusinessUpdate?.(next);
      onRunComplete?.(run);
      await saveBusiness(next);
    } finally {
      setRunningAll(false);
    }
  };

  return (
    <div className="space-y-3">
      <div className="grid gap-2 sm:grid-cols-2">
        {tasks.map((task) => (
          <TaskBox
            key={task.id}
            task={task}
            roleName={roleName}
            roleGroup={roleGroup}
            business={business}
            disabled={runningAll || (runningTaskId !== null && runningTaskId !== task.id)}
            onRunningChange={(running) => setRunningTaskId(running ? task.id : null)}
            lastReceipt={lastReceiptForTask(task.id)}
            onRunComplete={onRunComplete}
            onBusinessUpdate={onBusinessUpdate}
          />
        ))}
      </div>
      {showRunAll && tasks.length > 1 ? (
        <Button
          size="sm"
          variant="outline"
          className="w-full gap-2"
          disabled={anyRunning}
          onClick={runAll}
        >
          {runningAll ? (
            <>
              <Loader2 className="h-3.5 w-3.5 animate-spin" />
              Running all {tasks.length} tasks…
            </>
          ) : (
            <>
              <Play className="h-3.5 w-3.5" />
              Run all {tasks.length} tasks
            </>
          )}
        </Button>
      ) : null}
    </div>
  );
}
