/**
 * DevQALoop - Developer ↔ QA Review Loop Interface
 *
 * Visualizes the iterative review cycle between Developer and QA agents,
 * showing iteration count, feedback history, and current state.
 *
 * @module components/DevQALoop
 */

import { useState } from 'react';
import { useTeamStore } from '../store/teamStore';
import type { DevQALoop as DevQALoopType, ReviewFeedback, ReviewIssue } from '../types/team';
import {
  RefreshCw, CheckCircle, XCircle, AlertTriangle,
  Clock, MessageSquare, FileCode, Bug, Lightbulb, ChevronDown, ChevronUp,
  Send, ThumbsUp, ThumbsDown, AlertOctagon,
} from 'lucide-react';

// === Sub-Components ===

interface FeedbackItemProps {
  feedback: ReviewFeedback;
  iteration: number;
  isExpanded: boolean;
  onToggle: () => void;
}

function FeedbackItem({ feedback, iteration, isExpanded, onToggle }: FeedbackItemProps) {
  const verdictColors = {
    approved: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300',
    needs_work: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-300',
    rejected: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300',
  };

  const verdictIcons = {
    approved: <ThumbsUp className="w-4 h-4" />,
    needs_work: <AlertTriangle className="w-4 h-4" />,
    rejected: <ThumbsDown className="w-4 h-4" />,
  };

  const severityColors = {
    critical: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300',
    major: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300',
    minor: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-300',
    suggestion: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300',
  };

  return (
    <div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
      <button
        onClick={onToggle}
        className="w-full px-4 py-3 flex items-center justify-between bg-gray-50 dark:bg-gray-800"
      >
        <div className="flex items-center gap-3">
          <span className="w-6 h-6 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center text-xs font-medium">
            {iteration}
          </span>
          <span className={`px-2 py-0.5 rounded text-xs font-medium flex items-center gap-1 ${verdictColors[feedback.verdict]}`}>
            {verdictIcons[feedback.verdict]}
            {feedback.verdict.replace('_', ' ')}
          </span>
          <span className="text-xs text-gray-500 dark:text-gray-400">
            {new Date(feedback.reviewedAt).toLocaleString()}
          </span>
        </div>
        {isExpanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
      </button>

      {isExpanded && (
        <div className="p-4 space-y-4">
          {/* Comments */}
          {feedback.comments.length > 0 && (
            <div>
              <h5 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Comments</h5>
              <ul className="space-y-2">
                {feedback.comments.map((comment, idx) => (
                  <li key={idx} className="text-sm text-gray-600 dark:text-gray-400 flex items-start gap-2">
                    <MessageSquare className="w-4 h-4 mt-0.5 text-gray-400" />
                    {comment}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {/* Issues */}
          {feedback.issues.length > 0 && (
            <div>
              <h5 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Issues ({feedback.issues.length})</h5>
              <div className="space-y-2">
                {feedback.issues.map((issue, idx) => (
                  <div key={idx} className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <div className="flex items-center gap-2 mb-1">
                      <span className={`px-1.5 py-0.5 rounded text-xs font-medium ${severityColors[issue.severity]}`}>
                        {issue.severity}
                      </span>
                      {issue.file && (
                        <span className="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1">
                          <FileCode className="w-3 h-3" />
                          {issue.file}{issue.line ? `:${issue.line}` : ''}
                        </span>
                      )}
                    </div>
                    <p className="text-sm text-gray-700 dark:text-gray-300">{issue.description}</p>
                    {issue.suggestion && (
                      <p className="mt-1 text-xs text-blue-600 dark:text-blue-400 flex items-start gap-1">
                        <Lightbulb className="w-3 h-3 mt-0.5" />
                        {issue.suggestion}
                      </p>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

interface ReviewFormProps {
  loopId: string;
  teamId: string;
  onSubmit: (feedback: Omit<ReviewFeedback, 'reviewedAt' | 'reviewerId'>) => void;
  onCancel: () => void;
}

function ReviewForm({ loopId: _loopId, teamId: _teamId, onSubmit, onCancel }: ReviewFormProps) {
  const [verdict, setVerdict] = useState<ReviewFeedback['verdict']>('needs_work');
  const [comment, setComment] = useState('');
  const [issues, setIssues] = useState<ReviewIssue[]>([]);
  const [newIssue, setNewIssue] = useState<Partial<ReviewIssue>>({});

  const handleAddIssue = () => {
    if (!newIssue.description) return;
    setIssues([...issues, {
      severity: newIssue.severity || 'minor',
      description: newIssue.description,
      file: newIssue.file,
      line: newIssue.line,
      suggestion: newIssue.suggestion,
    } as ReviewIssue]);
    setNewIssue({});
  };

  const handleSubmit = () => {
    onSubmit({
      verdict,
      comments: comment ? [comment] : [],
      issues,
    });
  };

  return (
    <div className="p-4 bg-gray-50 dark:bg-gray-800 rounded-lg space-y-4">
      <h4 className="font-medium text-gray-900 dark:text-white">Submit Review</h4>

      {/* Verdict */}
      <div>
        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Verdict</label>
        <div className="flex gap-2">
          {(['approved', 'needs_work', 'rejected'] as const).map(v => (
            <button
              key={v}
              onClick={() => setVerdict(v)}
              className={`px-3 py-1.5 rounded-lg text-sm font-medium ${
                verdict === v
                  ? v === 'approved'
                    ? 'bg-green-500 text-white'
                    : v === 'needs_work'
                    ? 'bg-yellow-500 text-white'
                    : 'bg-red-500 text-white'
                  : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
              }`}
            >
              {v.replace('_', ' ')}
            </button>
          ))}
        </div>
      </div>

      {/* Comment */}
      <div>
        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Comment</label>
        <textarea
          value={comment}
          onChange={(e) => setComment(e.target.value)}
          placeholder="Overall feedback..."
          className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
          rows={3}
        />
      </div>

      {/* Add Issue */}
      <div>
        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Add Issue</label>
        <div className="grid grid-cols-2 gap-2">
          <select
            value={newIssue.severity || 'minor'}
            onChange={(e) => setNewIssue({ ...newIssue, severity: e.target.value as ReviewIssue['severity'] })}
            className="px-2 py-1.5 border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white text-sm"
          >
            <option value="critical">Critical</option>
            <option value="major">Major</option>
            <option value="minor">Minor</option>
            <option value="suggestion">Suggestion</option>
          </select>
          <input
            type="text"
            value={newIssue.file || ''}
            onChange={(e) => setNewIssue({ ...newIssue, file: e.target.value })}
            placeholder="File path"
            className="px-2 py-1.5 border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white text-sm"
          />
          <input
            type="number"
            value={newIssue.line || ''}
            onChange={(e) => setNewIssue({ ...newIssue, line: parseInt(e.target.value) || undefined })}
            placeholder="Line"
            className="px-2 py-1.5 border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white text-sm"
          />
          <input
            type="text"
            value={newIssue.description || ''}
            onChange={(e) => setNewIssue({ ...newIssue, description: e.target.value })}
            placeholder="Issue description"
            className="px-2 py-1.5 border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white text-sm"
          />
        </div>
        <input
          type="text"
          value={newIssue.suggestion || ''}
          onChange={(e) => setNewIssue({ ...newIssue, suggestion: e.target.value })}
          placeholder="Suggested fix (optional)"
          className="w-full mt-2 px-2 py-1.5 border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white text-sm"
        />
        <button
          onClick={handleAddIssue}
          disabled={!newIssue.description}
          className="mt-2 px-3 py-1.5 text-sm bg-gray-200 dark:bg-gray-700 rounded hover:bg-gray-300 dark:hover:bg-gray-600 disabled:opacity-50"
        >
          Add Issue
        </button>
      </div>

      {/* Issues List */}
      {issues.length > 0 && (
        <div className="space-y-1">
          {issues.map((issue, idx) => (
            <div key={idx} className="flex items-center gap-2 text-sm p-2 bg-white dark:bg-gray-900 rounded">
              <span className="px-1.5 py-0.5 rounded text-xs bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-300">
                {issue.severity}
              </span>
              <span className="flex-1 truncate">{issue.description}</span>
              <button
                onClick={() => setIssues(issues.filter((_, i) => i !== idx))}
                className="text-gray-400 hover:text-red-500"
              >
                <XCircle className="w-4 h-4" />
              </button>
            </div>
          ))}
        </div>
      )}

      {/* Actions */}
      <div className="flex gap-2">
        <button
          onClick={handleSubmit}
          className="flex-1 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 flex items-center justify-center gap-2"
        >
          <Send className="w-4 h-4" />
          Submit Review
        </button>
        <button
          onClick={onCancel}
          className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700"
        >
          Cancel
        </button>
      </div>
    </div>
  );
}

// === Main Component ===

interface DevQALoopPanelProps {
  loop: DevQALoopType;
  teamId: string;
  developerName: string;
  reviewerName: string;
  taskTitle: string;
}

export function DevQALoopPanel({ loop, teamId, developerName, reviewerName, taskTitle }: DevQALoopPanelProps) {
  const [expandedFeedback, setExpandedFeedback] = useState<number | null>(null);
  const [showReviewForm, setShowReviewForm] = useState(false);

  const { submitReview, updateLoopState } = useTeamStore();

  const stateConfig = {
    idle: { color: 'gray', icon: <Clock className="w-5 h-5" />, label: 'Idle' },
    developing: { color: 'blue', icon: <FileCode className="w-5 h-5" />, label: 'Developing' },
    reviewing: { color: 'yellow', icon: <RefreshCw className="w-5 h-5" />, label: 'Reviewing' },
    revising: { color: 'orange', icon: <Bug className="w-5 h-5" />, label: 'Revising' },
    approved: { color: 'green', icon: <CheckCircle className="w-5 h-5" />, label: 'Approved' },
    escalated: { color: 'red', icon: <AlertOctagon className="w-5 h-5" />, label: 'Escalated' },
  };

  const config = stateConfig[loop.state];

  const handleSubmitReview = async (feedback: Omit<ReviewFeedback, 'reviewedAt' | 'reviewerId'>) => {
    await submitReview(teamId, loop.id, feedback);
    setShowReviewForm(false);
  };

  const handleCompleteRevision = async () => {
    await updateLoopState(teamId, loop.id, 'reviewing');
  };

  return (
    <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
      {/* Header */}
      <div className={`px-4 py-3 bg-${config.color}-50 dark:bg-${config.color}-900/20 border-b border-${config.color}-200 dark:border-${config.color}-800`}>
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className={`text-${config.color}-500`}>{config.icon}</div>
            <div>
              <h3 className="font-semibold text-gray-900 dark:text-white">Dev↔QA Loop</h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">{taskTitle}</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <span className={`px-2 py-1 rounded text-xs font-medium bg-${config.color}-100 text-${config.color}-700 dark:bg-${config.color}-900/30 dark:text-${config.color}-300`}>
              {config.label}
            </span>
            <span className="text-sm text-gray-500 dark:text-gray-400">
              Iteration {loop.iterationCount + 1}/{loop.maxIterations}
            </span>
          </div>
        </div>
      </div>

      {/* Flow Visualization */}
      <div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
              ['developing', 'revising'].includes(loop.state) ? 'bg-blue-500 text-white' : 'bg-gray-200 dark:bg-gray-700'
            }`}>
              <FileCode className="w-4 h-4" />
            </div>
            <div className="text-sm">
              <div className="font-medium text-gray-900 dark:text-white">{developerName}</div>
              <div className="text-xs text-gray-500">Developer</div>
            </div>
          </div>

          <div className="flex-1 mx-4 flex items-center">
            <div className="flex-1 h-0.5 bg-gray-200 dark:bg-gray-700" />
            <RefreshCw className={`w-5 h-5 mx-2 ${loop.state === 'reviewing' ? 'text-yellow-500 animate-spin' : 'text-gray-400'}`} />
            <div className="flex-1 h-0.5 bg-gray-200 dark:bg-gray-700" />
          </div>

          <div className="flex items-center gap-2">
            <div className="text-sm text-right">
              <div className="font-medium text-gray-900 dark:text-white">{reviewerName}</div>
              <div className="text-xs text-gray-500">QA Reviewer</div>
            </div>
            <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
              loop.state === 'reviewing' ? 'bg-yellow-500 text-white' : 'bg-gray-200 dark:bg-gray-700'
            }`}>
              <Bug className="w-4 h-4" />
            </div>
          </div>
        </div>
      </div>

      {/* Progress Bar */}
      <div className="px-4 py-2 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center gap-1">
          {Array.from({ length: loop.maxIterations }).map((_, i) => (
            <div
              key={i}
              className={`flex-1 h-2 rounded ${
                i < loop.iterationCount
                  ? 'bg-yellow-400'
                  : i === loop.iterationCount && ['developing', 'reviewing', 'revising'].includes(loop.state)
                  ? 'bg-blue-400'
                  : 'bg-gray-200 dark:bg-gray-700'
              }`}
            />
          ))}
        </div>
      </div>

      {/* Feedback History */}
      <div className="p-4 space-y-3 max-h-64 overflow-y-auto">
        <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300">Feedback History</h4>
        {loop.feedbackHistory.length === 0 ? (
          <div className="text-sm text-gray-500 dark:text-gray-400 text-center py-4">
            No feedback yet. First review pending.
          </div>
        ) : (
          loop.feedbackHistory.map((feedback, idx) => (
            <FeedbackItem
              key={idx}
              feedback={feedback}
              iteration={idx + 1}
              isExpanded={expandedFeedback === idx}
              onToggle={() => setExpandedFeedback(expandedFeedback === idx ? null : idx)}
            />
          ))
        )}
      </div>

      {/* Actions */}
      <div className="p-4 border-t border-gray-200 dark:border-gray-700">
        {loop.state === 'escalated' ? (
          <div className="p-3 bg-red-50 dark:bg-red-900/20 rounded-lg text-center">
            <AlertOctagon className="w-6 h-6 mx-auto mb-2 text-red-500" />
            <p className="text-sm text-red-700 dark:text-red-300">
              Maximum iterations reached. Human intervention required.
            </p>
          </div>
        ) : loop.state === 'approved' ? (
          <div className="p-3 bg-green-50 dark:bg-green-900/20 rounded-lg text-center">
            <CheckCircle className="w-6 h-6 mx-auto mb-2 text-green-500" />
            <p className="text-sm text-green-700 dark:text-green-300">
              Task approved and completed!
            </p>
          </div>
        ) : loop.state === 'reviewing' && !showReviewForm ? (
          <button
            onClick={() => setShowReviewForm(true)}
            className="w-full px-4 py-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 flex items-center justify-center gap-2"
          >
            <RefreshCw className="w-4 h-4" />
            Submit Review
          </button>
        ) : loop.state === 'revising' ? (
          <button
            onClick={handleCompleteRevision}
            className="w-full px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 flex items-center justify-center gap-2"
          >
            <CheckCircle className="w-4 h-4" />
            Complete Revision
          </button>
        ) : showReviewForm ? (
          <ReviewForm
            loopId={loop.id}
            teamId={teamId}
            onSubmit={handleSubmitReview}
            onCancel={() => setShowReviewForm(false)}
          />
        ) : null}
      </div>
    </div>
  );
}

export default DevQALoopPanel;
