'use client';

import { useCallback, useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Eye, EyeOff } from 'lucide-react';
import { formatApiErrorMessage } from '@/components/shared/formatApiError';
import { Button } from '@/components/ui/shared/Button';
import type { LabCaseComment } from '@/types/cases';

interface LabCaseCommentsPanelProps {
  caseId: string;
  canPost: boolean;
  canToggleVisibility: boolean;
  loadComments: () => Promise<LabCaseComment[]>;
  onPost: (body: string, visibleToClinic?: boolean) => Promise<LabCaseComment>;
  onToggleVisibility?: (commentId: string, visible: boolean) => Promise<LabCaseComment>;
  onError?: (message: string) => void;
}

export function LabCaseCommentsPanel({
  caseId,
  canPost,
  canToggleVisibility,
  loadComments,
  onPost,
  onToggleVisibility,
  onError,
}: LabCaseCommentsPanelProps) {
  const t = useTranslations('caseComments');
  const [comments, setComments] = useState<LabCaseComment[]>([]);
  const [loading, setLoading] = useState(false);
  const [posting, setPosting] = useState(false);
  const [body, setBody] = useState('');
  const [visibleToClinic, setVisibleToClinic] = useState(false);

  const refresh = useCallback(async () => {
    setLoading(true);
    try {
      const items = await loadComments();
      setComments(items);
    } catch (error: unknown) {
      onError?.(formatApiErrorMessage(error, t('errorLoad')));
    } finally {
      setLoading(false);
    }
  }, [loadComments, onError, t]);

  useEffect(() => {
    void refresh();
  }, [caseId, refresh]);

  async function handlePost() {
    const trimmed = body.trim();
    if (!trimmed || !canPost) return;
    setPosting(true);
    try {
      const created = await onPost(trimmed, visibleToClinic);
      setComments((prev) => [...prev, created]);
      setBody('');
      setVisibleToClinic(false);
    } catch (error: unknown) {
      onError?.(formatApiErrorMessage(error, t('errorPost')));
    } finally {
      setPosting(false);
    }
  }

  async function handleToggle(comment: LabCaseComment) {
    if (!onToggleVisibility || !canToggleVisibility) return;
    try {
      const updated = await onToggleVisibility(comment.id, !comment.visibleToClinic);
      setComments((prev) => prev.map((c) => (c.id === updated.id ? updated : c)));
    } catch (error: unknown) {
      onError?.(formatApiErrorMessage(error, t('errorToggle')));
    }
  }

  return (
    <div className="space-y-3">
      <h4 className="text-sm font-medium text-text-primary">{t('title')}</h4>

      {loading ? (
        <p className="text-xs text-text-muted">…</p>
      ) : comments.length === 0 ? (
        <p className="text-xs text-text-muted">{t('empty')}</p>
      ) : (
        <ul className="space-y-2 max-h-48 overflow-y-auto">
          {comments.map((comment) => (
            <li
              key={comment.id}
              className="rounded-md border border-border bg-background p-2 text-sm"
            >
              <div className="flex items-start justify-between gap-2">
                <div className="min-w-0 flex-1">
                  <div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-text-muted">
                    <span className="font-medium text-text-secondary">
                      {comment.authorSide === 'LAB' ? t('labAuthor') : t('clinicAuthor')}
                      {comment.authorName ? ` · ${comment.authorName}` : ''}
                    </span>
                    {comment.visibleToClinic ? (
                      <span className="text-primary">{t('clinicCanSee')}</span>
                    ) : (
                      <span>{t('hiddenFromClinic')}</span>
                    )}
                  </div>
                  <p className="mt-1 text-text-primary whitespace-pre-wrap">{comment.body}</p>
                </div>
                {canToggleVisibility && comment.canToggleVisibility && onToggleVisibility ? (
                  <button
                    type="button"
                    onClick={() => void handleToggle(comment)}
                    className="shrink-0 p-1 rounded hover:bg-border text-text-muted"
                    title={
                      comment.visibleToClinic ? t('makeHidden') : t('makeVisible')
                    }
                    aria-label={
                      comment.visibleToClinic ? t('makeHidden') : t('makeVisible')
                    }
                  >
                    {comment.visibleToClinic ? (
                      <Eye className="h-4 w-4" />
                    ) : (
                      <EyeOff className="h-4 w-4" />
                    )}
                  </button>
                ) : null}
              </div>
            </li>
          ))}
        </ul>
      )}

      {canPost ? (
        <div className="space-y-2 border-t border-border pt-2">
          <textarea
            value={body}
            onChange={(e) => setBody(e.target.value)}
            placeholder={t('placeholder')}
            rows={2}
            className="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm resize-none"
          />
          {canToggleVisibility ? (
            <label className="flex items-center gap-2 text-xs text-text-muted cursor-pointer">
              <input
                type="checkbox"
                checked={visibleToClinic}
                onChange={(e) => setVisibleToClinic(e.target.checked)}
              />
              {t('visibleToClinicToggle')}
            </label>
          ) : null}
          <Button
            type="button"
            size="sm"
            disabled={posting || !body.trim()}
            onClick={() => void handlePost()}
          >
            {t('post')}
          </Button>
        </div>
      ) : null}
    </div>
  );
}
