import { useState, useRef, useCallback } from 'react';
import { Card } from '../components/Card';
import { ProgressBar } from '../components/ProgressBar';
import { Badge } from '../components/Badge';
import { useCompliance } from '../context/ComplianceContext';
import { CHECKLIST_DATA } from '@cra-compliance/shared';

// Checklist item IDs that have matching document templates, keyed to template ID
const DOCUMENT_LINKS: Record<string, { templateId: string; label: string }> = {
  'vh-1':   { templateId: 'vulnerability-disclosure-policy', label: 'Generate VDP' },
  'vh-2':   { templateId: 'security-txt',                    label: 'Generate security.txt' },
  'vh-3':   { templateId: 'incident-response-plan',          label: 'Generate IRP' },
  'conf-3': { templateId: 'declaration-of-conformity',       label: 'Generate Declaration' },
  'doc-2':  { templateId: 'sbom',                            label: 'Generate SBOM' },
};

interface ChecklistProps {
  onNavigate?: (page: 'documents') => void;
}

export function Checklist({ onNavigate }: ChecklistProps) {
  const { progress, loading, loadError, toggleItem, saveNotes, savingItemId, savingNotesId, totalItems, completedItems } = useCompliance();
  const [expandedItems, setExpandedItems] = useState<Set<string>>(new Set());

  const toggleExpanded = (itemId: string) => {
    setExpandedItems((prev) => {
      const next = new Set(prev);
      if (next.has(itemId)) next.delete(itemId); else next.add(itemId);
      return next;
    });
  };

  if (loading) return <div className="cra-loading">Loading checklist...</div>;

  if (loadError) {
    return (
      <div className="cra-alert cra-alert-error" style={{ margin: '24px' }}>
        <strong>Could not load checklist progress.</strong> {loadError}
        <br />
        <small>If this keeps happening, try deactivating and reactivating the plugin to rebuild the database tables.</small>
      </div>
    );
  }

  return (
    <div className="cra-checklist-page">
      <div className="cra-page-header">
        <h2>Compliance Checklist</h2>
        <p>
          Work through each item to ensure your WordPress plugin meets EU Cyber
          Resilience Act requirements.
        </p>
      </div>

      <Card>
        <ProgressBar
          value={completedItems}
          max={totalItems}
          label="Overall Compliance Progress"
          size="lg"
        />
        <p style={{ color: 'var(--cra-muted)', marginTop: '8px', fontSize: '14px' }}>
          {completedItems} of {totalItems} items completed
        </p>
      </Card>

      {CHECKLIST_DATA.map((category) => {
        const catCompleted = category.items.filter((item) => progress[item.id]?.completed).length;

        return (
          <Card
            key={category.id}
            title={category.title}
            description={category.description}
            actions={
              <Badge variant={catCompleted === category.items.length ? 'success' : 'info'}>
                {catCompleted}/{category.items.length}
              </Badge>
            }
          >
            <div className="cra-checklist-items">
              {category.items.map((item) => {
                const isCompleted = progress[item.id]?.completed || false;
                const isExpanded = expandedItems.has(item.id);
                const isSaving = savingItemId === item.id;
                const isSavingNotes = savingNotesId === item.id;
                const currentNotes = progress[item.id]?.notes || '';
                const docLink = DOCUMENT_LINKS[item.id];

                return (
                  <div key={item.id} className={`cra-checklist-item ${isCompleted ? 'completed' : ''}`}>
                    <div className="cra-checklist-item-header">
                      <label className="cra-checkbox-label">
                        <input
                          type="checkbox"
                          checked={isCompleted}
                          onChange={() => toggleItem(item)}
                          disabled={isSaving}
                          className="cra-checkbox"
                        />
                        <span className={`cra-checklist-title ${isCompleted ? 'line-through' : ''}`}>
                          {item.title}
                        </span>
                      </label>
                      <div className="cra-checklist-item-meta">
                        {item.automated && <Badge variant="info" size="sm">Automatable</Badge>}
                        <Badge variant="neutral" size="sm">{item.cra_article}</Badge>
                        {currentNotes && !isExpanded && (
                          <span className="cra-note-indicator" title="Has evidence note">●</span>
                        )}
                        <button className="cra-btn-text" onClick={() => toggleExpanded(item.id)}>
                          {isExpanded ? 'Less' : 'More'}
                        </button>
                      </div>
                    </div>
                    <p className="cra-checklist-description">{item.description}</p>
                    {isExpanded && (
                      <div className="cra-checklist-help">
                        <strong>How to do this:</strong>
                        <p>{item.help_text}</p>
                        {docLink && onNavigate && (
                          <button
                            className="cra-btn cra-btn-sm"
                            style={{ marginTop: 8 }}
                            onClick={() => onNavigate('documents')}
                          >
                            {docLink.label} →
                          </button>
                        )}
                        <EvidenceNote
                          itemId={item.id}
                          initialValue={currentNotes}
                          onSave={saveNotes}
                          saving={isSavingNotes}
                        />
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </Card>
        );
      })}
    </div>
  );
}

interface EvidenceNoteProps {
  itemId: string;
  initialValue: string;
  onSave: (itemId: string, notes: string) => Promise<void>;
  saving: boolean;
}

function EvidenceNote({ itemId, initialValue, onSave, saving }: EvidenceNoteProps) {
  const [value, setValue] = useState(initialValue);
  const [saved, setSaved] = useState(false);
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const handleChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const next = e.target.value;
    setValue(next);
    setSaved(false);
    if (timerRef.current) clearTimeout(timerRef.current);
    timerRef.current = setTimeout(async () => {
      await onSave(itemId, next);
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
    }, 800);
  }, [itemId, onSave]);

  return (
    <div className="cra-evidence-note">
      <label className="cra-evidence-label">
        Evidence / Notes
        {saving && <span className="cra-evidence-status">Saving…</span>}
        {saved && !saving && <span className="cra-evidence-status cra-evidence-saved">Saved ✓</span>}
      </label>
      <textarea
        className="cra-input cra-evidence-textarea"
        placeholder="Add a link, reference, or note to document how you've completed this item (e.g. https://example.com/security or 'VDP published in readme.txt')"
        value={value}
        onChange={handleChange}
        rows={3}
      />
    </div>
  );
}
