'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth-context';
import {
  getItem,
  updateItem,
  updateItemStatus,
  listComments,
  addComment,
  toggleVote,
  type TrackerItem,
  type Comment,
} from '@/lib/tracker-client';

const STATUSES = ['open', 'in_progress', 'done', 'closed', 'wont_fix'] as const;
const PRIORITIES = ['critical', 'high', 'medium', 'low'] as const;
const VISIBILITIES = ['internal', 'public'] as const;

export default function ItemDetailPage() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const { token } = useAuth();

  const [item, setItem] = useState<TrackerItem | null>(null);
  const [comments, setComments] = useState<Comment[]>([]);
  const [newComment, setNewComment] = useState('');
  const [error, setError] = useState('');
  const [editing, setEditing] = useState(false);
  const [editTitle, setEditTitle] = useState('');
  const [editDescription, setEditDescription] = useState('');

  useEffect(() => {
    if (!token || !id) return;
    getItem(id)
      .then(setItem)
      .catch(err => setError(err.message));
    listComments(id)
      .then(res => setComments(res.comments))
      .catch(() => {});
  }, [token, id]);

  const handleStatusChange = async (status: string) => {
    if (!id) return;
    try {
      const updated = await updateItemStatus(id, status);
      setItem(updated);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to update status');
    }
  };

  const handlePriorityChange = async (priority: string) => {
    if (!id) return;
    try {
      const updated = await updateItem(id, { priority } as Partial<TrackerItem>);
      setItem(updated);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to update priority');
    }
  };

  const handleVisibilityChange = async (visibility: string) => {
    if (!id) return;
    try {
      const updated = await updateItem(id, { visibility } as Partial<TrackerItem>);
      setItem(updated);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to update visibility');
    }
  };

  const handleSaveEdit = async () => {
    if (!id) return;
    try {
      const updated = await updateItem(id, {
        title: editTitle,
        description: editDescription,
      } as Partial<TrackerItem>);
      setItem(updated);
      setEditing(false);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to update');
    }
  };

  const handleAddComment = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!id || !newComment.trim()) return;
    try {
      const comment = await addComment(id, newComment);
      setComments(prev => [...prev, comment]);
      setNewComment('');
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to add comment');
    }
  };

  const handleVote = async () => {
    if (!id) return;
    try {
      const res = await toggleVote(id);
      setItem(prev => (prev ? { ...prev, voteCount: res.voteCount } : prev));
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to vote');
    }
  };

  if (!item) {
    return (
      <div className="flex min-h-[400px] items-center justify-center text-muted-foreground">
        {error || 'Loading...'}
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-3xl space-y-6">
      {/* Back */}
      <button
        onClick={() => router.back()}
        className="text-sm text-muted-foreground hover:text-foreground"
      >
        ← Back
      </button>

      {error && (
        <div className="rounded-md bg-destructive/10 px-4 py-3 text-sm text-destructive">
          {error}
        </div>
      )}

      {/* Header */}
      <div className="space-y-2">
        {editing ? (
          <div className="space-y-3">
            <input
              type="text"
              value={editTitle}
              onChange={e => setEditTitle(e.target.value)}
              className="w-full rounded-md border border-input bg-background px-3 py-2 text-lg font-bold outline-none ring-ring focus:ring-2"
            />
            <textarea
              value={editDescription}
              onChange={e => setEditDescription(e.target.value)}
              rows={6}
              className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm outline-none ring-ring focus:ring-2"
            />
            <div className="flex gap-2">
              <button
                onClick={handleSaveEdit}
                className="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground hover:bg-primary/90"
              >
                Save
              </button>
              <button
                onClick={() => setEditing(false)}
                className="rounded-md px-3 py-1.5 text-sm text-muted-foreground hover:bg-accent"
              >
                Cancel
              </button>
            </div>
          </div>
        ) : (
          <>
            <div className="flex items-start justify-between">
              <h1 className="text-2xl font-bold tracking-tight">{item.title}</h1>
              <button
                onClick={() => {
                  setEditTitle(item.title);
                  setEditDescription(item.description);
                  setEditing(true);
                }}
                className="rounded-md px-3 py-1.5 text-sm text-muted-foreground hover:bg-accent"
              >
                Edit
              </button>
            </div>
            {item.description && (
              <p className="whitespace-pre-wrap text-sm text-muted-foreground">
                {item.description}
              </p>
            )}
          </>
        )}
      </div>

      {/* Meta */}
      <div className="grid grid-cols-2 gap-4 rounded-xl border border-border bg-card p-4 md:grid-cols-5">
        <div>
          <div className="text-xs font-medium text-muted-foreground">Type</div>
          <div className="mt-1 text-sm font-medium capitalize">{item.type}</div>
        </div>
        <div>
          <div className="text-xs font-medium text-muted-foreground">Status</div>
          <select
            value={item.status}
            onChange={e => handleStatusChange(e.target.value)}
            className="mt-1 rounded border border-input bg-background px-2 py-1 text-sm"
          >
            {STATUSES.map(s => (
              <option key={s} value={s}>
                {s.replace(/_/g, ' ')}
              </option>
            ))}
          </select>
        </div>
        <div>
          <div className="text-xs font-medium text-muted-foreground">Priority</div>
          <select
            value={item.priority}
            onChange={e => handlePriorityChange(e.target.value)}
            className="mt-1 rounded border border-input bg-background px-2 py-1 text-sm"
          >
            {PRIORITIES.map(p => (
              <option key={p} value={p}>
                {p}
              </option>
            ))}
          </select>
        </div>
        <div>
          <div className="text-xs font-medium text-muted-foreground">Visibility</div>
          <select
            value={item.visibility || 'internal'}
            onChange={e => handleVisibilityChange(e.target.value)}
            className="mt-1 rounded border border-input bg-background px-2 py-1 text-sm"
          >
            {VISIBILITIES.map(v => (
              <option key={v} value={v}>
                {v === 'public' ? '🌐 Public' : '🔒 Internal'}
              </option>
            ))}
          </select>
        </div>
        <div>
          <div className="text-xs font-medium text-muted-foreground">Votes</div>
          <button
            onClick={handleVote}
            className="mt-1 flex items-center gap-1 rounded-md border border-input bg-background px-2 py-1 text-sm hover:bg-accent"
          >
            ▲ {item.voteCount}
          </button>
        </div>
      </div>

      {/* Labels & meta */}
      <div className="flex flex-wrap gap-4 text-xs text-muted-foreground">
        {item.labels.length > 0 && (
          <div className="flex gap-1">
            {item.labels.map(l => (
              <span key={l} className="rounded-full bg-muted px-2 py-0.5">
                {l}
              </span>
            ))}
          </div>
        )}
        <span>Created: {new Date(item.createdAt).toLocaleDateString()}</span>
        {item.assignee && <span>Assigned: {item.assignee}</span>}
        {item.targetRelease && <span>Release: {item.targetRelease}</span>}
      </div>

      {/* Comments */}
      <div className="space-y-4">
        <h2 className="text-lg font-semibold">Comments ({comments.length})</h2>

        {comments.map(c => (
          <div key={c.id} className="rounded-lg border border-border bg-card p-4">
            <div className="mb-2 flex items-center justify-between text-xs text-muted-foreground">
              <span>{c.authorEmail || c.authorId}</span>
              <span>{new Date(c.createdAt).toLocaleString()}</span>
            </div>
            <p className="whitespace-pre-wrap text-sm">{c.body}</p>
          </div>
        ))}

        <form onSubmit={handleAddComment} className="space-y-2">
          <textarea
            value={newComment}
            onChange={e => setNewComment(e.target.value)}
            placeholder="Add a comment..."
            rows={3}
            className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm outline-none ring-ring focus:ring-2"
          />
          <button
            type="submit"
            disabled={!newComment.trim()}
            className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
          >
            Comment
          </button>
        </form>
      </div>
    </div>
  );
}
