"use client";

import { useState } from "react";
import { Linkedin, Twitter, Facebook, Instagram, ChevronDown, ChevronUp, Send, Eye, EyeOff } from "lucide-react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import type { Network, EngagementType, EngagementStatus } from "@/lib/types";

const NETWORK_ICONS: Record<Network, typeof Linkedin> = {
  LINKEDIN: Linkedin,
  TWITTER: Twitter,
  FACEBOOK: Facebook,
  INSTAGRAM: Instagram,
};

const TYPE_LABELS: Record<EngagementType, string> = {
  COMMENT: "Comment",
  MENTION: "Mention",
  DM: "Direct Message",
};

interface InboxItemProps {
  id: string;
  authorName: string;
  authorAvatar?: string;
  network: Network;
  type: EngagementType;
  content: string;
  status: EngagementStatus;
  createdAt: string;
  postContent?: string;
  onReply?: (id: string, content: string) => void;
  onMarkRead?: (id: string) => void;
  onIgnore?: (id: string) => void;
  readOnly?: boolean;
}

export function InboxItem({
  id, authorName, network, type, content, status, createdAt,
  postContent, onReply, onMarkRead, onIgnore, readOnly,
}: InboxItemProps) {
  const [expanded, setExpanded] = useState(false);
  const [replyText, setReplyText] = useState("");

  const NetworkIcon = NETWORK_ICONS[network];
  const timeAgo = getTimeAgo(new Date(createdAt));

  return (
    <div className={`border rounded-lg p-3 transition-colors ${status === "UNREAD" ? "bg-blue-50/50 border-blue-200" : ""}`}>
      <button onClick={() => setExpanded(!expanded)} className="w-full text-left">
        <div className="flex items-start gap-3">
          <Avatar className="h-8 w-8">
            <AvatarFallback className="text-xs">{authorName.slice(0, 2).toUpperCase()}</AvatarFallback>
          </Avatar>
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="font-medium text-sm">{authorName}</span>
              <NetworkIcon className="h-3.5 w-3.5 text-muted-foreground" />
              <Badge variant="outline" className="text-[10px] px-1.5 py-0">{TYPE_LABELS[type]}</Badge>
              {status === "UNREAD" && <span className="h-2 w-2 rounded-full bg-blue-500" />}
              <span className="text-xs text-muted-foreground ml-auto">{timeAgo}</span>
            </div>
            <p className="text-sm text-muted-foreground truncate mt-0.5">{content}</p>
          </div>
          {expanded ? <ChevronUp className="h-4 w-4 text-muted-foreground mt-1" /> : <ChevronDown className="h-4 w-4 text-muted-foreground mt-1" />}
        </div>
      </button>

      {expanded && (
        <div className="mt-3 space-y-3">
          <Separator />
          <p className="text-sm whitespace-pre-wrap">{content}</p>
          {postContent && (
            <div className="rounded bg-muted/50 p-2 text-xs text-muted-foreground">
              <span className="font-medium">Original post:</span> {postContent}
            </div>
          )}
          {!readOnly && (
            <div className="flex items-center gap-2">
              <input
                value={replyText}
                onChange={(e) => setReplyText(e.target.value)}
                placeholder="Type a reply..."
                className="flex-1 rounded-md border px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
              />
              <Button
                size="sm"
                disabled={!replyText.trim()}
                onClick={() => { onReply?.(id, replyText); setReplyText(""); }}
              >
                <Send className="h-3.5 w-3.5 mr-1" /> Reply
              </Button>
              <Button size="sm" variant="outline" onClick={() => onMarkRead?.(id)}>
                <Eye className="h-3.5 w-3.5" />
              </Button>
              <Button size="sm" variant="outline" onClick={() => onIgnore?.(id)}>
                <EyeOff className="h-3.5 w-3.5" />
              </Button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function getTimeAgo(date: Date): string {
  const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
  if (seconds < 60) return "just now";
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  return `${days}d ago`;
}
