'use client';

import React from 'react';
import {
  FiArrowUp,
  FiArrowDown,
  FiTrash2,
  FiCircle,
  FiPaperclip,
  FiPlus,
} from 'react-icons/fi';
import EvidenceZone from './EvidenceZone';
import type { EditableEntry, NcSource } from './findings.types';
import { isDraft } from './findings.types';

// ═══════════════════════════════════════════════════════════════════════
// FindingDetail v6.1 — right-panel editor
// ═══════════════════════════════════════════════════════════════════════

interface Props {
  entry: EditableEntry;
  index: number;
  source: NcSource;
  ncId: number;
  hasPrev: boolean;
  hasNext: boolean;
  onPrev: () => void;
  onNext: () => void;
  onChange: (patch: Partial<EditableEntry>) => void;
  onFileChanged: (newPath: string | null) => void;
  onDelete: () => void;
  // NEW — optional. Wire this to the same handler your sidebar's
  // "+ Add more NC items" button uses, so a fresh draft can be added
  // straight from the toolbar without scrolling the sidebar.
  onAddNew?: () => void;
}

export default function FindingDetail({
  entry,
  index,
  source,
  ncId,
  hasPrev,
  hasNext,
  onPrev,
  onNext,
  onChange,
  onFileChanged,
  onDelete,
  onAddNew,
}: Props) {
  const statementLen = entry.ncr_statement.length;
  const draft = isDraft(entry);
  const [drafting, setDrafting] = React.useState(false);

  const API_BASE =
    process.env.NEXT_PUBLIC_API_URL?.replace(/\/api$/, "") ||
    process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/api$/, "") ||
    "";

  const handleAiDraft = async () => {
    const note = entry.ncr_statement.trim();
    if (!note) {
      alert("Type a short note in the NCR statement first, then click Draft.");
      return;
    }
    setDrafting(true);
    try {
      const token =
        localStorage.getItem("access_token") ||
        sessionStorage.getItem("access_token") ||
        localStorage.getItem("token") ||
        localStorage.getItem("authToken") ||
        "";
      const res = await fetch(`${API_BASE}/api/previous-nc/ai/draft`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
        },
        body: JSON.stringify({ nc_type: entry.nc_type || "", note }),
      });
      if (!res.ok) throw new Error(`Draft failed (${res.status})`);
      const d = await res.json();
      // Fill the fields — auditor reviews and edits after this
      onChange({
        ncr_statement: d.statement || entry.ncr_statement,
        criteria_clause: d.clause || entry.criteria_clause,
        corrective_action: d.corrective_action || entry.corrective_action,
        nc_type: d.nc_type || entry.nc_type,
      });
    } catch (e: any) {
      alert(e?.message || "AI draft failed");
    } finally {
      setDrafting(false);
    }
  };
  return (
    <div
      style={{
        background: '#fff',
        border: '1px solid #e2e8f0',
        borderRadius: 12,
        overflow: 'hidden',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {/* ── Detail header ── */}
      <div
        style={{
          padding: '14px 18px',
          borderBottom: '1px solid #f1f5f9',
          background: '#fafbfc',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: 10,
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: 28,
              height: 28,
              background: draft ? '#92400e' : '#0b1220',
              color: '#fff',
              borderRadius: 7,
              fontSize: 11,
              fontWeight: 700,
              fontFamily: "'JetBrains Mono', monospace",
              letterSpacing: '0.04em',
            }}
          >
            {draft ? 'NEW' : String(index).padStart(2, '0')}
          </span>
          <div>
            <div
              style={{
                fontSize: 13,
                fontWeight: 600,
                color: '#0b1220',
                lineHeight: 1.2,
                display: 'flex',
                alignItems: 'center',
                gap: 8,
              }}
            >
              {draft ? 'New finding (draft)' : 'Finding details'}
              {draft && (
                <span
                  style={{
                    fontSize: 9,
                    padding: '2px 7px',
                    background: '#fef3c7',
                    color: '#92400e',
                    borderRadius: 99,
                    fontWeight: 700,
                    letterSpacing: '0.04em',
                  }}
                >
                  DRAFT
                </span>
              )}
            </div>
            <div
              style={{
                fontSize: 10,
                color: '#94a3b8',
                marginTop: 2,
                display: 'inline-flex',
                alignItems: 'center',
                gap: 6,
                fontFamily: "'JetBrains Mono', monospace",
              }}
            >
              <span>
                {draft ? 'Saved on Phase 2' : `entry_id: ${entry.id}`}
              </span>
              {entry._dirty && !draft && (
                <>
                  <span
                    style={{
                      width: 3,
                      height: 3,
                      background: '#cbd5e1',
                      borderRadius: 50,
                    }}
                  />
                  <span
                    style={{
                      color: '#92400e',
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: 3,
                    }}
                  >
                    <FiCircle fill="#f59e0b" color="#f59e0b" size={7} />
                    Modified
                  </span>
                </>
              )}
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
          {onAddNew && (
            <button
              onClick={onAddNew}
              title="Add another finding — no need to scroll the sidebar"
              style={{
                background: '#185FA5',
                border: '1px solid #185FA5',
                borderRadius: 6,
                padding: '5px 10px',
                color: '#fff',
                cursor: 'pointer',
                fontSize: 11,
                fontWeight: 600,
                display: 'inline-flex',
                alignItems: 'center',
                gap: 4,
              }}
            >
              <FiPlus size={12} /> Add item
            </button>
          )}
          <button
            onClick={onPrev}
            disabled={!hasPrev}
            title="Previous finding (↑)"
            style={navBtn(!hasPrev)}
          >
            <FiArrowUp size={11} /> Prev
          </button>
          <button
            onClick={onNext}
            disabled={!hasNext}
            title="Next finding (↓)"
            style={navBtn(!hasNext)}
          >
            Next <FiArrowDown size={11} />
          </button>
          <button
            onClick={onDelete}
            title={draft ? 'Discard draft' : 'Delete this finding'}
            aria-label="Delete finding"
            style={{
              background: '#fff',
              border: '1px solid #fecaca',
              borderRadius: 6,
              padding: '5px 9px',
              color: '#dc2626',
              cursor: 'pointer',
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: 11,
              fontWeight: 500,
              gap: 4,
              transition: 'all 0.12s',
            }}
            onMouseEnter={(e) => {
              (e.currentTarget as HTMLButtonElement).style.background = '#fef2f2';
            }}
            onMouseLeave={(e) => {
              (e.currentTarget as HTMLButtonElement).style.background = '#fff';
            }}
          >
            <FiTrash2 size={12} />
            {draft && <span style={{ marginLeft: 2 }}>Discard</span>}
          </button>
        </div>
      </div>

      {/* ── Detail body ── */}
      <div style={{ padding: '18px 18px 22px' }}>
        {/* Segmented buttons: Type + Status */}
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: 12,
            marginBottom: 18,
          }}
        >
          <div>
            <Label>NC Type</Label>
            <SegmentedButtons
              value={entry.nc_type}
              options={[
                { value: 'Major', label: 'Major', color: '#A32D2D', bg: '#FCEBEB' },
                { value: 'Minor', label: 'Minor', color: '#854F0B', bg: '#FAEEDA' },
                { value: 'Observation', label: 'Observation', color: '#0C447C', bg: '#E6F1FB' },
              ]}
              onChange={(v) => onChange({ nc_type: v })}
            />
          </div>
          <div>
            <Label>Status</Label>
            <SegmentedButtons
              value={entry.status}
              options={[
                { value: 'open', label: 'Open', color: '#A32D2D', bg: '#FCEBEB', dot: '#dc2626' },
                { value: 'pending', label: 'Pending', color: '#854F0B', bg: '#FAEEDA', dot: '#d97706' },
                { value: 'closed', label: 'Closed', color: '#0F6E56', bg: '#E1F5EE', dot: '#16a34a' },
              ]}
              onChange={(v) =>
                onChange({ status: v as 'open' | 'pending' | 'closed' })
              }
            />
          </div>
        </div>

        {/* NCR statement */}
        <div style={{ marginBottom: 16 }}>
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'baseline',
              marginBottom: 6,
            }}
          >
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <Label inline>
                NCR statement <span style={{ color: "#dc2626" }}>*</span>
              </Label>
              <button
                onClick={handleAiDraft}
                disabled={drafting}
                style={{
                  background: drafting ? "#cbd5e1" : "#185FA5",
                  color: "#fff",
                  border: "none",
                  borderRadius: 6,
                  padding: "3px 9px",
                  fontSize: 10,
                  fontWeight: 700,
                  cursor: drafting ? "wait" : "pointer",
                  display: "inline-flex",
                  alignItems: "center",
                  gap: 4,
                  letterSpacing: "0.02em",
                }}
                title="Type a few words in the statement, then click to draft"
              >
                {drafting ? "Drafting…" : "✨ Draft with AI"}
              </button>
            </div>
            <span
              style={{
                fontSize: 10,
                color: statementLen > 950 ? '#dc2626' : '#94a3b8',
                fontFamily: "'JetBrains Mono', monospace",
                fontWeight: 500,
              }}
            >
              {statementLen} / 1000
            </span>
          </div>
          <textarea
            value={entry.ncr_statement}
            onChange={(e) => onChange({ ncr_statement: e.target.value })}
            placeholder="Describe the non-conformity finding observed during the audit…"
            maxLength={1000}
            style={{
              ...inputStyle(),
              minHeight: 86,
              resize: 'vertical',
              lineHeight: 1.55,
              padding: '10px 12px',
            }}
          />
        </div>

        {/* Criteria + Corrective */}
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: 12,
            marginBottom: 18,
          }}
        >
          <div>
            <Label>Criteria clause</Label>
            <input
              value={entry.criteria_clause}
              onChange={(e) => onChange({ criteria_clause: e.target.value })}
              placeholder="e.g. Clause 7.2 - QHSE"
              style={{
                ...inputStyle(),
                fontFamily: "'JetBrains Mono', monospace",
                fontSize: 12,
              }}
            />
          </div>
          <div>
            <Label>Corrective action</Label>
            <input
              value={entry.corrective_action}
              onChange={(e) => onChange({ corrective_action: e.target.value })}
              placeholder="Auditee's proposed action"
              style={inputStyle()}
            />
          </div>
        </div>

        {/* ── EVIDENCE SECTION (clear, prominent) ── */}
        <div
          style={{
            marginTop: 22,
            paddingTop: 20,
            borderTop: '1px solid #e2e8f0',
          }}
        >
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 11,
              marginBottom: 14,
            }}
          >
            <div
              style={{
                width: 32,
                height: 32,
                background: '#185FA5',
                borderRadius: 8,
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
                flexShrink: 0,
              }}
            >
              <FiPaperclip size={15} color="#fff" />
            </div>
            <div style={{ flex: 1 }}>
              <div
                style={{
                  fontSize: 13,
                  fontWeight: 700,
                  color: '#0b1220',
                  letterSpacing: '-0.005em',
                }}
              >
                Evidence
              </div>
              <div
                style={{
                  fontSize: 11,
                  color: '#64748b',
                  marginTop: 1,
                }}
              >
                Upload supporting documents for this finding (PDF, Word, Excel, Images, ZIP)
              </div>
            </div>
            {entry.document_path && (
              <span
                style={{
                  fontSize: 9,
                  padding: '3px 8px',
                  background: '#dcfce7',
                  color: '#15803d',
                  borderRadius: 99,
                  fontWeight: 700,
                  letterSpacing: '0.04em',
                }}
              >
                FILE ATTACHED
              </span>
            )}
          </div>

          {draft ? (
            <div
              style={{
                padding: '20px',
                background: '#fafbfc',
                border: '1px dashed #cbd5e1',
                borderRadius: 9,
                textAlign: 'center',
                fontSize: 11,
                color: '#94a3b8',
              }}
            >
              Save the finding first to upload evidence files.
            </div>
          ) : (
            <EvidenceZone
              source={source}
              ncId={ncId}
              entryId={entry.id}
              documentPath={entry.document_path}
              onChange={onFileChanged}
            />
          )}
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// Sub-components
// ═══════════════════════════════════════════════════════════════════════

interface SegOption {
  value: string;
  label: string;
  color: string;
  bg: string;
  dot?: string;
}

function SegmentedButtons({
  value,
  options,
  onChange,
}: {
  value: string;
  options: SegOption[];
  onChange: (v: string) => void;
}) {
  return (
    <div style={{ display: 'flex', gap: 5 }}>
      {options.map((opt) => {
        const active = value === opt.value;
        return (
          <button
            key={opt.value}
            onClick={() => onChange(opt.value)}
            style={{
              flex: 1,
              padding: '7px 10px',
              fontSize: 11,
              background: active ? opt.bg : '#fff',
              color: active ? opt.color : '#475569',
              border: `1px solid ${active ? opt.color : '#e2e8f0'}`,
              borderRadius: 6,
              fontWeight: active ? 700 : 500,
              cursor: 'pointer',
              transition: 'all 0.12s',
              boxShadow: active ? `0 0 0 2px ${opt.color}15` : 'none',
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 4,
            }}
          >
            {active && opt.dot && (
              <span
                style={{
                  width: 6,
                  height: 6,
                  background: opt.dot,
                  borderRadius: 50,
                  display: 'inline-block',
                }}
              />
            )}
            {opt.label}
          </button>
        );
      })}
    </div>
  );
}

function Label({
  children,
  inline,
}: {
  children: React.ReactNode;
  inline?: boolean;
}) {
  return (
    <div
      style={{
        fontSize: 10,
        fontWeight: 700,
        color: '#64748b',
        textTransform: 'uppercase',
        letterSpacing: '0.08em',
        marginBottom: inline ? 0 : 6,
      }}
    >
      {children}
    </div>
  );
}

function navBtn(disabled: boolean): React.CSSProperties {
  return {
    background: '#fff',
    border: '1px solid #e2e8f0',
    borderRadius: 6,
    padding: '5px 9px',
    color: disabled ? '#cbd5e1' : '#475569',
    cursor: disabled ? 'not-allowed' : 'pointer',
    fontSize: 11,
    fontWeight: 500,
    display: 'inline-flex',
    alignItems: 'center',
    gap: 4,
    opacity: disabled ? 0.6 : 1,
    transition: 'all 0.12s',
  };
}

function inputStyle(): React.CSSProperties {
  return {
    width: '100%',
    background: '#fff',
    border: '1px solid #e2e8f0',
    borderRadius: 7,
    padding: '8px 11px',
    fontSize: 13,
    fontWeight: 500,
    color: '#0b1220',
    outline: 'none',
    fontFamily: 'inherit',
    lineHeight: 1.5,
    boxSizing: 'border-box',
    transition: 'border-color 0.12s',
  };
}