"use client";

import { useState } from "react";
import { CheckCircle2, Circle, TrendingUp, TrendingDown, Minus, Copy, Check } from "lucide-react";
import { Summary, ActionItem } from "@/types";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { SimpleTooltip } from "@/components/ui/tooltip";
import { useMeetingsStore } from "@/store";
import { cn } from "@/lib/utils";

interface SummaryPanelProps {
  summary: Summary;
  meetingId: string;
}

const sentimentConfig = {
  positive: { icon: TrendingUp,   label: "Positive", className: "text-green-600 dark:text-green-400" },
  neutral:  { icon: Minus,        label: "Neutral",  className: "text-gray-600 dark:text-gray-400" },
  negative: { icon: TrendingDown, label: "Negative", className: "text-red-600 dark:text-red-400" },
};

function ActionItemRow({ item, meetingId }: { item: ActionItem; meetingId: string }) {
  const toggleActionItem = useMeetingsStore((s) => s.toggleActionItem);
  const dueDate = item.dueDate ? new Date(item.dueDate) : null;
  return (
    <div className="flex items-start gap-3 py-2">
      <SimpleTooltip content={item.completed ? "Mark as incomplete" : "Mark as complete"}>
        <button onClick={() => toggleActionItem(meetingId, item.id)} className="mt-0.5 shrink-0 cursor-pointer">
          {item.completed
            ? <CheckCircle2 className="h-5 w-5 text-green-600 dark:text-green-400" />
            : <Circle className="h-5 w-5 text-gray-400 dark:text-gray-500" />
          }
        </button>
      </SimpleTooltip>
      <div className="flex-1 min-w-0">
        <p className={cn("text-sm text-gray-900 dark:text-gray-100", item.completed && "line-through text-gray-400 dark:text-gray-500")}>
          {item.text}
        </p>
        <div className="flex items-center gap-2 mt-1">
          {item.assignee && (
            <SimpleTooltip content={`Assigned to ${item.assignee}`}>
              <span className="cursor-default text-xs text-gray-500 dark:text-gray-400">@{item.assignee}</span>
            </SimpleTooltip>
          )}
          {dueDate && (
            <SimpleTooltip content={`Due date: ${dueDate.toLocaleString("en-US", { dateStyle: "medium", timeStyle: "short" })}`}>
              <Badge variant="outline" className="cursor-default text-[10px] py-0">
                Due {dueDate.toLocaleDateString("en-US", { month: "short", day: "numeric" })}
              </Badge>
            </SimpleTooltip>
          )}
        </div>
      </div>
    </div>
  );
}

export function SummaryPanel({ summary, meetingId }: SummaryPanelProps) {
  const [copied, setCopied] = useState(false);
  const { icon: SentimentIcon, label: sentimentLabel, className: sentimentClass } = sentimentConfig[summary.sentiment];
  const pendingCount = summary.actionItems.filter((a) => !a.completed).length;

  const handleCopy = () => {
    const text = [
      "MEETING SUMMARY", "",
      summary.overview, "",
      "KEY POINTS:", ...summary.keyPoints.map((p) => `• ${p}`), "",
      "DECISIONS:", ...summary.decisions.map((d) => `• ${d}`), "",
      "ACTION ITEMS:", ...summary.actionItems.map((a) => `• ${a.text}${a.assignee ? ` (@${a.assignee})` : ""}${a.dueDate ? ` - Due: ${a.dueDate}` : ""}`),
    ].join("\n");
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(text);
    } else {
      const el = document.createElement("textarea");
      el.value = text;
      el.style.position = "fixed";
      el.style.opacity = "0";
      document.body.appendChild(el);
      el.focus();
      el.select();
      document.execCommand("copy");
      document.body.removeChild(el);
    }
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const sectionTitle = "text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide";

  return (
    <div className="space-y-4">
      {/* Overview */}
      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between flex-wrap gap-2">
            <CardTitle className={sectionTitle}>Overview</CardTitle>
            <div className="flex items-center gap-3">
              <SimpleTooltip content={`Overall meeting sentiment: ${sentimentLabel}`}>
                <span className={cn("flex cursor-default items-center gap-1 text-sm font-medium", sentimentClass)}>
                  <SentimentIcon className="h-4 w-4" />{sentimentLabel}
                </span>
              </SimpleTooltip>
              <SimpleTooltip content={copied ? "Copied to clipboard" : "Copy summary to clipboard"}>
                <Button variant="ghost" size="sm" onClick={handleCopy} className="h-8 gap-1.5">
                  {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
                  {copied ? "Copied" : "Copy"}
                </Button>
              </SimpleTooltip>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-gray-700 dark:text-gray-300 leading-relaxed">{summary.overview}</p>
        </CardContent>
      </Card>

      {/* Key Points */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className={sectionTitle}>Key Points</CardTitle>
        </CardHeader>
        <CardContent>
          <ul className="space-y-2">
            {summary.keyPoints.map((point, i) => (
              <li key={i} className="flex items-start gap-2 text-sm text-gray-700 dark:text-gray-300">
                <span className="mt-1.5 h-1.5 w-1.5 rounded-full bg-blue-600 dark:bg-blue-400 shrink-0" />
                {point}
              </li>
            ))}
          </ul>
        </CardContent>
      </Card>

      {/* Decisions */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className={sectionTitle}>Decisions Made</CardTitle>
        </CardHeader>
        <CardContent>
          <ul className="space-y-2">
            {summary.decisions.map((decision, i) => (
              <li key={i} className="flex items-start gap-2 text-sm text-gray-700 dark:text-gray-300">
                <span className="mt-1.5 h-1.5 w-1.5 rounded-full bg-green-600 dark:bg-green-400 shrink-0" />
                {decision}
              </li>
            ))}
          </ul>
        </CardContent>
      </Card>

      {/* Action Items */}
      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <CardTitle className={sectionTitle}>Action Items</CardTitle>
            <SimpleTooltip content={`${pendingCount} pending action item${pendingCount !== 1 ? "s" : ""} out of ${summary.actionItems.length}`}>
              <Badge variant="secondary" className="cursor-default">{pendingCount} pending</Badge>
            </SimpleTooltip>
          </div>
        </CardHeader>
        <CardContent>
          <div className="divide-y divide-gray-100 dark:divide-gray-800">
            {summary.actionItems.map((item) => (
              <ActionItemRow key={item.id} item={item} meetingId={meetingId} />
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
