'use client';

import { useState } from 'react';
import {
  ChevronDown,
  ChevronRight,
  CheckCircle2,
  Clock,
  AlertCircle,
  ClipboardCheck,
  ExternalLink,
} from 'lucide-react';
import { cn } from '@/lib/cn';
import { manualServices, type ManualCheck } from '../_data/manual-tests';
import type { Feedback, TestingIssue } from '../_hooks/useTestFeedback';

type FilterType = 'all' | 'pending' | 'ok' | 'issue';

interface Props {
  feedbacks: Record<string, Feedback>;
  onOk: (checkId: string, tester: string) => void;
  onIssue: (issue: Omit<TestingIssue, 'id' | 'resolved'>) => void;
  onClear: (checkId: string) => void;
}

export function ManualTestsSection({ feedbacks, onOk, onIssue, onClear }: Props) {
  const [expandedService, setExpandedService] = useState<string | null>(null);
  const [expandedSection, setExpandedSection] = useState<string | null>(null);
  const [issueFormId, setIssueFormId] = useState<string | null>(null);
  const [filter, setFilter] = useState<FilterType>('all');

  const totalChecks = manualServices.reduce(
    (s, svc) => s + svc.sections.reduce((ss, sec) => ss + sec.checks.length, 0),
    0,
  );
  const okCount = Object.values(feedbacks).filter((f) => f.status === 'ok').length;
  const issueCount = Object.values(feedbacks).filter((f) => f.status === 'issue').length;

  const matchesFilter = (checkId: string) => {
    if (filter === 'all') return true;
    const fb = feedbacks[checkId];
    if (filter === 'pending') return !fb;
    if (filter === 'ok') return fb?.status === 'ok';
    if (filter === 'issue') return fb?.status === 'issue';
    return true;
  };

  return (
    <div className="bg-card rounded-xl p-6 shadow-sm border border-border mb-8">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <ClipboardCheck className="h-5 w-5 text-primary" />
          <h2 className="text-lg font-semibold text-text">Ручное тестирование</h2>
        </div>
        <span className="text-sm text-muted">
          {okCount + issueCount}/{totalChecks} проверено
        </span>
      </div>

      {/* Filters */}
      <div className="flex gap-1 mb-4">
        {([
          { key: 'all' as const, label: 'Все' },
          { key: 'pending' as const, label: `Ожидает (${totalChecks - okCount - issueCount})` },
          { key: 'ok' as const, label: `ОК (${okCount})` },
          { key: 'issue' as const, label: `Замечания (${issueCount})` },
        ]).map((f) => (
          <button
            key={f.key}
            onClick={() => setFilter(f.key)}
            className={cn(
              'px-3 py-1 text-xs font-medium rounded-full transition-colors',
              filter === f.key
                ? 'bg-primary text-white'
                : 'bg-muted/10 text-muted hover:bg-muted/20',
            )}
          >
            {f.label}
          </button>
        ))}
      </div>

      {/* Services */}
      <div className="space-y-2">
        {manualServices.map((svc) => {
          const svcChecks = svc.sections.flatMap((s) => s.checks);
          const svcOk = svcChecks.filter((c) => feedbacks[c.id]?.status === 'ok').length;
          const svcIssue = svcChecks.filter((c) => feedbacks[c.id]?.status === 'issue').length;
          const svcVisible = svcChecks.filter((c) => matchesFilter(c.id));
          if (filter !== 'all' && svcVisible.length === 0) return null;
          const isOpen = expandedService === svc.id;

          return (
            <div key={svc.id} className="border border-border rounded-lg overflow-hidden">
              <button
                onClick={() => setExpandedService(isOpen ? null : svc.id)}
                className="w-full flex items-center gap-3 px-4 py-3 hover:bg-background transition-colors"
              >
                {isOpen ? (
                  <ChevronDown className="h-4 w-4 text-muted shrink-0" />
                ) : (
                  <ChevronRight className="h-4 w-4 text-muted shrink-0" />
                )}
                <span className="text-sm font-medium text-text flex-1 text-left">
                  {svc.name}
                </span>
                <a
                  href={svc.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  onClick={(e) => e.stopPropagation()}
                  className="text-xs text-primary hover:underline flex items-center gap-1 mr-2"
                >
                  <ExternalLink className="h-3 w-3" />
                </a>
                <div className="flex items-center gap-1.5">
                  {svcOk > 0 && (
                    <span className="text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-success/10 text-success">
                      {svcOk} OK
                    </span>
                  )}
                  {svcIssue > 0 && (
                    <span className="text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-error/10 text-error">
                      {svcIssue} !!!
                    </span>
                  )}
                  <span className="text-xs text-muted">
                    {svcOk + svcIssue}/{svcChecks.length}
                  </span>
                </div>
              </button>

              {isOpen && (
                <div className="border-t border-border/50">
                  {svc.sections.map((sec) => {
                    const secVisible = sec.checks.filter((c) => matchesFilter(c.id));
                    if (filter !== 'all' && secVisible.length === 0) return null;
                    const secOpen = expandedSection === sec.id;

                    return (
                      <div key={sec.id} className="border-b border-border/30 last:border-b-0">
                        <button
                          onClick={() => setExpandedSection(secOpen ? null : sec.id)}
                          className="w-full flex items-center gap-2 px-6 py-2 hover:bg-background/50 transition-colors"
                        >
                          {secOpen ? (
                            <ChevronDown className="h-3 w-3 text-muted" />
                          ) : (
                            <ChevronRight className="h-3 w-3 text-muted" />
                          )}
                          <span className="text-sm text-text">{sec.name}</span>
                          {sec.url && (
                            <a
                              href={sec.url}
                              target="_blank"
                              rel="noopener noreferrer"
                              onClick={(e) => e.stopPropagation()}
                              className="text-xs text-primary hover:underline flex items-center gap-0.5 ml-2"
                            >
                              <ExternalLink className="h-3 w-3" />
                              Открыть
                            </a>
                          )}
                          <span className="text-[11px] text-muted ml-auto">
                            {secVisible.length} проверок
                          </span>
                        </button>

                        {secOpen && (
                          <div className="px-6 pb-3 space-y-3">
                            {sec.checks
                              .filter((c) => matchesFilter(c.id))
                              .map((check) => (
                                <CheckItem
                                  key={check.id}
                                  check={check}
                                  service={svc.name}
                                  section={sec.name}
                                  feedback={feedbacks[check.id]}
                                  isIssueFormOpen={issueFormId === check.id}
                                  onOpenIssueForm={() => setIssueFormId(check.id)}
                                  onCloseIssueForm={() => setIssueFormId(null)}
                                  onOk={onOk}
                                  onIssue={onIssue}
                                  onClear={onClear}
                                />
                              ))}
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function CheckItem({
  check,
  service,
  section,
  feedback,
  isIssueFormOpen,
  onOpenIssueForm,
  onCloseIssueForm,
  onOk,
  onIssue,
  onClear,
}: {
  check: ManualCheck;
  service: string;
  section: string;
  feedback?: Feedback;
  isIssueFormOpen: boolean;
  onOpenIssueForm: () => void;
  onCloseIssueForm: () => void;
  onOk: (checkId: string, tester: string) => void;
  onIssue: (issue: Omit<TestingIssue, 'id' | 'resolved'>) => void;
  onClear: (checkId: string) => void;
}) {
  const [tester, setTester] = useState('');
  const [comment, setComment] = useState('');

  const handleSubmitIssue = () => {
    if (!comment.trim() || !tester.trim()) return;
    onIssue({
      checkId: check.id,
      service,
      section,
      instruction: check.instruction,
      comment: comment.trim(),
      tester: tester.trim(),
      date: new Date().toISOString(),
    });
    setComment('');
    setTester('');
    onCloseIssueForm();
  };

  const handleOk = () => {
    const name = feedback?.tester || prompt('Ваше имя:') || 'Тестер';
    onOk(check.id, name);
  };

  return (
    <div className="bg-background/50 rounded-lg p-3 border border-border/50">
      <div className="flex items-start gap-2">
        {feedback?.status === 'ok' ? (
          <CheckCircle2 className="h-4 w-4 text-success shrink-0 mt-0.5" />
        ) : feedback?.status === 'issue' ? (
          <AlertCircle className="h-4 w-4 text-error shrink-0 mt-0.5" />
        ) : (
          <Clock className="h-4 w-4 text-muted shrink-0 mt-0.5" />
        )}
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-1.5">
            <p className="text-sm text-text">{check.instruction}</p>
            {check.url && (
              <a
                href={check.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-primary hover:text-primary/80 shrink-0"
                title="Открыть страницу"
              >
                <ExternalLink className="h-3.5 w-3.5" />
              </a>
            )}
          </div>
          <p className="text-xs text-muted mt-0.5">
            Ожидается: {check.expectedResult}
          </p>

          {feedback && (
            <div className="mt-1.5 flex items-center gap-2 text-xs">
              <span
                className={cn(
                  'font-semibold px-2 py-0.5 rounded-full',
                  feedback.status === 'ok'
                    ? 'bg-success/10 text-success'
                    : 'bg-error/10 text-error',
                )}
              >
                {feedback.status === 'ok' ? 'OK' : 'Замечание'}
              </span>
              <span className="text-muted">{feedback.tester}</span>
              <button
                onClick={() => onClear(check.id)}
                className="text-muted hover:text-text underline"
              >
                Сбросить
              </button>
            </div>
          )}

          {feedback?.status === 'issue' && feedback.comment && (
            <p className="text-xs text-error mt-1 bg-error/10 px-2 py-1 rounded">
              {feedback.comment}
            </p>
          )}
        </div>

        {!feedback && (
          <div className="flex gap-1.5 shrink-0">
            <button
              onClick={handleOk}
              className="text-xs font-medium px-3 py-1.5 rounded-lg border border-success/20 bg-success/10 text-success hover:bg-success/20 transition-colors"
            >
              OK
            </button>
            <button
              onClick={onOpenIssueForm}
              className="text-xs font-medium px-3 py-1.5 rounded-lg border border-warning/20 bg-warning/10 text-warning hover:bg-warning/20 transition-colors"
            >
              Замечание
            </button>
          </div>
        )}
      </div>

      {isIssueFormOpen && !feedback && (
        <div className="mt-3 pl-6 space-y-2">
          <input
            type="text"
            placeholder="Ваше имя"
            value={tester}
            onChange={(e) => setTester(e.target.value)}
            className="w-full text-sm px-3 py-2 border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30"
          />
          <textarea
            placeholder="Опишите проблему..."
            value={comment}
            onChange={(e) => setComment(e.target.value)}
            rows={2}
            className="w-full text-sm px-3 py-2 border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30 resize-none"
          />
          <div className="flex gap-2">
            <button
              onClick={handleSubmitIssue}
              disabled={!comment.trim() || !tester.trim()}
              className="text-xs font-medium px-4 py-2 rounded-lg bg-primary text-white hover:bg-primary/90 transition-colors disabled:opacity-50"
            >
              Отправить замечание
            </button>
            <button
              onClick={onCloseIssueForm}
              className="text-xs font-medium px-4 py-2 rounded-lg border border-border text-muted hover:bg-muted/20 transition-colors"
            >
              Отмена
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
