'use client';

import { useCallback, useEffect, useState } from 'react';
import { MessageSquare, Send } from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { Button } from '@/components/ui/button';
import { UserAvatar } from '@/components/ui/UserAvatar';
import { api, ApiError } from '@/lib/api';
import { formatRelativeTime } from '@/lib/utils';
import { PortalSection } from '@/components/portal/Portal';

export interface JobCommentItem {
  id: string;
  content: string;
  createdAt: string;
  user: {
    id: string;
    firstName: string;
    lastName: string;
    avatarUrl?: string | null;
    role: 'CUSTOMER' | 'WORKER' | 'ADMIN';
  };
}

interface JobCommentsSectionProps {
  jobId: string;
  /** Portal section wrapper (customer) vs plain card styling */
  variant?: 'portal' | 'worker';
}

export function JobCommentsSection({ jobId, variant = 'portal' }: JobCommentsSectionProps) {
  const { user } = useAuth();
  const [comments, setComments] = useState<JobCommentItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [forbidden, setForbidden] = useState(false);
  const [content, setContent] = useState('');
  const [posting, setPosting] = useState(false);
  const [error, setError] = useState('');

  const loadComments = useCallback(async () => {
    setLoading(true);
    setForbidden(false);
    try {
      const res = await api<{ data: JobCommentItem[] }>(`/jobs/${jobId}/comments`);
      setComments(res.data);
    } catch (err) {
      if (err instanceof ApiError && err.status === 403) {
        setForbidden(true);
      } else {
        console.error(err);
      }
    } finally {
      setLoading(false);
    }
  }, [jobId]);

  useEffect(() => {
    loadComments();
  }, [loadComments]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const trimmed = content.trim();
    if (!trimmed || posting) return;

    setPosting(true);
    setError('');
    try {
      const res = await api<{ data: JobCommentItem }>(`/jobs/${jobId}/comments`, {
        method: 'POST',
        body: JSON.stringify({ content: trimmed }),
      });
      setComments((prev) => [...prev, res.data]);
      setContent('');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Could not post comment');
    } finally {
      setPosting(false);
    }
  };

  if (forbidden || (!loading && !user)) {
    return null;
  }

  const body = (
    <div className="space-y-4">
      {loading ? (
        <p className="text-sm text-muted">Loading comments…</p>
      ) : comments.length === 0 ? (
        <p className="text-sm text-muted">
          {variant === 'worker'
            ? 'No comments yet. Ask the customer a question about this job — other workers can see the thread too.'
            : 'No comments yet. Workers can ask questions here before applying, and you can reply.'}
        </p>
      ) : (
        <ul className="space-y-3">
          {comments.map((comment) => {
            const isOwn = comment.user.id === user?.id;
            const roleLabel =
              comment.user.role === 'WORKER'
                ? 'Worker'
                : comment.user.role === 'CUSTOMER'
                  ? 'Customer'
                  : 'User';

            return (
              <li
                key={comment.id}
                className={`flex gap-3 rounded-xl border px-3 py-3 sm:px-4 ${
                  isOwn ? 'border-primary/20 bg-primary/5' : 'border-border bg-slate-50/80'
                }`}
              >
                <UserAvatar
                  firstName={comment.user.firstName}
                  lastName={comment.user.lastName}
                  avatarUrl={comment.user.avatarUrl}
                  size="xs"
                />
                <div className="min-w-0 flex-1">
                  <div className="flex flex-wrap items-center gap-x-2 gap-y-0.5">
                    <p className="text-sm font-semibold text-slate-900">
                      {comment.user.firstName} {comment.user.lastName}
                      {isOwn ? <span className="font-normal text-muted"> (you)</span> : null}
                    </p>
                    <span className="text-[10px] font-semibold uppercase tracking-wide text-muted">
                      {roleLabel}
                    </span>
                    <span className="text-xs text-muted">
                      · {formatRelativeTime(comment.createdAt)}
                    </span>
                  </div>
                  <p className="mt-1 whitespace-pre-wrap text-sm leading-relaxed text-slate-700">
                    {comment.content}
                  </p>
                </div>
              </li>
            );
          })}
        </ul>
      )}

      {error ? (
        <p className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2">
          {error}
        </p>
      ) : null}

      <form onSubmit={handleSubmit} className="space-y-2 pt-1">
        <label htmlFor={`job-comment-${jobId}`} className="sr-only">
          Write a comment
        </label>
        <textarea
          id={`job-comment-${jobId}`}
          value={content}
          onChange={(e) => setContent(e.target.value)}
          placeholder={
            user?.role === 'CUSTOMER'
              ? 'Reply to workers or share an update…'
              : 'Ask the customer a question…'
          }
          rows={3}
          maxLength={2000}
          className="w-full resize-none rounded-lg border border-border px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
        />
        <div className="flex items-center justify-between gap-2">
          <p className="text-xs text-muted">
            {variant === 'worker'
              ? 'Visible to the customer and other workers on this job.'
              : 'Visible to you and workers viewing this job.'}
          </p>
          <Button type="submit" size="sm" className="gap-1.5 shrink-0" disabled={posting || !content.trim()}>
            <Send className="h-4 w-4" />
            {posting ? 'Posting…' : 'Post comment'}
          </Button>
        </div>
      </form>
    </div>
  );

  if (variant === 'worker') {
    return (
      <section className="rounded-xl border border-border bg-surface p-4 md:p-5 space-y-3">
        <div className="flex items-center gap-2">
          <MessageSquare className="h-5 w-5 text-primary" />
          <div>
            <h2 className="font-bold text-slate-900">Comments</h2>
            <p className="text-xs text-muted">Public Q&amp;A with the customer — other workers can read and reply</p>
          </div>
        </div>
        {body}
      </section>
    );
  }

  return (
    <PortalSection
      icon={MessageSquare}
      title="Comments"
      description="Workers can ask questions here; you can reply before hiring"
    >
      {body}
    </PortalSection>
  );
}
