'use client';
import React, { useCallback, useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import toast from 'react-hot-toast';
import {
  FiArrowLeft,
  FiSave,
  FiPlus,
  FiTrash2,
  FiInfo,
  FiList,
  FiChevronDown,
} from 'react-icons/fi';

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

function getAuthToken(): string {
  if (typeof window === 'undefined') return '';
  return (
    localStorage.getItem('access_token') ||
    sessionStorage.getItem('access_token') ||
    localStorage.getItem('token') ||
    localStorage.getItem('authToken') ||
    ''
  );
}

function authHeaders(): HeadersInit {
  const token = getAuthToken();
  return token
    ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }
    : { 'Content-Type': 'application/json' };
}

interface DraftFinding {
  ncr_statement: string;
  criteria_clause: string;
  corrective_action: string;
  nc_type: string;
  status: string;
}

interface AuditContext {
  audit_id: number;
  audit_code: string | null;
  audit_type: string | null;
  company_name: string | null;
}

const emptyFinding = (): DraftFinding => ({
  ncr_statement: '',
  criteria_clause: '',
  corrective_action: '',
  nc_type: '',
  status: 'open',
});

export default function RaiseNcPage() {
  const router = useRouter();
  const search = useSearchParams();
  const auditId = Number(search.get('audit_id') || '');

  const [ctx, setCtx] = useState<AuditContext | null>(null);
  const [loadingCtx, setLoadingCtx] = useState(true);
  const [ctxError, setCtxError] = useState<string | null>(null);

  // ── NC-level fields (same as edit's "Audit context") ──
  const [auditeeName, setAuditeeName] = useState('');
  const [auditType, setAuditType] = useState('');
  const [ncType, setNcType] = useState('Minor');
  const [followUpDate, setFollowUpDate] = useState('');
  const [dueDate, setDueDate] = useState('');
  const [followUpNotes, setFollowUpNotes] = useState('');
  const [remark, setRemark] = useState('');

  // ── Findings ──
  const [findings, setFindings] = useState<DraftFinding[]>([emptyFinding()]);

  const [saving, setSaving] = useState(false);
  const [draftingIndex, setDraftingIndex] = useState<number | null>(null);

  const handleAiDraft = async (i: number) => {
    const note = findings[i].ncr_statement.trim();
    if (!note) {
      toast.error('Type a short note in the NCR statement first, then click Draft.');
      return;
    }
    setDraftingIndex(i);
    try {
      const res = await fetch(`${API_BASE}/api/previous-nc/ai/draft`, {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify({
          nc_type: findings[i].nc_type || ncType || '',
          note,
        }),
      });
      if (!res.ok) throw new Error(`Draft failed (${res.status})`);
      const d = await res.json();
      if (d?.error) throw new Error('Model service unavailable');
      updateFinding(i, {
        ncr_statement: d.statement || findings[i].ncr_statement,
        criteria_clause: d.clause || findings[i].criteria_clause,
        corrective_action: d.corrective_action || findings[i].corrective_action,
        nc_type: d.nc_type || findings[i].nc_type,
      });
      toast.success('Draft generated — review and edit before saving.');
    } catch (e: any) {
      toast.error(e?.message || 'AI draft failed');
    } finally {
      setDraftingIndex(null);
    }
  };

  // ── Section toggles (match edit page) ──
  const [contextOpen, setContextOpen] = useState(true);

  // ─── Load audit context (auto-fill company + audit type) ──────────────
  const loadCtx = useCallback(async () => {
    if (!auditId) {
      setCtxError('No audit_id in URL.');
      setLoadingCtx(false);
      return;
    }
    setLoadingCtx(true);
    setCtxError(null);
    try {
      const res = await fetch(`${API_BASE}/api/audits/${auditId}/workspace`, {
        headers: authHeaders(),
        cache: 'no-store',
      });
      if (!res.ok) throw new Error(`Failed to load audit (${res.status})`);
      const data = await res.json();
      const row = data?.audit ?? data?.row ?? data ?? {};
      const at = row.audit_type ?? data?.audit_type ?? null;
      setCtx({
        audit_id: auditId,
        audit_code: row.audit_code ?? data?.audit_code ?? null,
        audit_type: at,
        company_name:
          row.company?.name ??
          row.company_name ??
          data?.company?.name ??
          data?.company_name ??
          null,
      });
      if (at) setAuditType(at);
    } catch (err: any) {
      setCtx({
        audit_id: auditId,
        audit_code: null,
        audit_type: null,
        company_name: null,
      });
      setCtxError(err?.message ?? 'Could not load audit context');
    } finally {
      setLoadingCtx(false);
    }
  }, [auditId]);

  useEffect(() => {
    loadCtx();
  }, [loadCtx]);

  // ─── Finding helpers ──────────────────────────────────────────────────
  const updateFinding = (i: number, patch: Partial<DraftFinding>) =>
    setFindings((prev) =>
      prev.map((f, idx) => (idx === i ? { ...f, ...patch } : f)),
    );
  const addFinding = () => setFindings((prev) => [...prev, emptyFinding()]);
  const removeFinding = (i: number) =>
    setFindings((prev) =>
      prev.length === 1 ? prev : prev.filter((_, idx) => idx !== i),
    );

  // ─── Submit ───────────────────────────────────────────────────────────
  const handleSubmit = async () => {
    if (!auditId) {
      toast.error('Missing audit id.');
      return;
    }
    const valid = findings.filter((f) => f.ncr_statement.trim());
    if (valid.length === 0) {
      toast.error('Add at least one finding with a statement.');
      return;
    }
    if (!ncType.trim()) {
      toast.error('Select an NC type.');
      return;
    }

    setSaving(true);
    try {
      const body = {
        audit_id: auditId,
        nc_type: ncType,
        status: 'open',
        auditee_name: auditeeName.trim() || null,
        follow_up_date: followUpDate || null,
        due_date: dueDate || null,
        follow_up_notes: followUpNotes.trim() || null,
        remark: remark.trim() || null,
        findings: valid.map((f) => ({
          ncr_statement: f.ncr_statement.trim(),
          criteria_clause: f.criteria_clause.trim() || undefined,
          corrective_action: f.corrective_action.trim() || undefined,
          nc_type: f.nc_type.trim() || undefined,
          status: f.status || 'open',
        })),
      };

      const res = await fetch(`${API_BASE}/api/previous-nc/new`, {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify(body),
      });
      if (!res.ok) {
        let detail = '';
        try {
          const b = await res.json();
          detail = Array.isArray(b?.message)
            ? b.message.join('; ')
            : b?.message || '';
        } catch {}
        throw new Error(detail || `Request failed (${res.status})`);
      }
      const result = await res.json();
      toast.success(
        `NC raised — ${result.findings_created} finding(s). Opening editor…`,
      );
      router.push(`/modules/previous-nc/edit?source=NEW&id=${result.nc_id}`);
    } catch (err: any) {
      toast.error(err?.message ?? 'Failed to raise NC');
      setSaving(false);
    }
  };

  // ─── Invalid link guard ───────────────────────────────────────────────
  if (!auditId) {
    return (
      <div style={{ padding: 60, textAlign: 'center', color: '#dc2626' }}>
        <h3 style={{ margin: '0 0 8px', color: '#111827' }}>Invalid link</h3>
        <p style={{ fontSize: 13 }}>No audit selected.</p>
        <button onClick={() => router.back()} style={btnStyle('secondary')}>
          Go back
        </button>
      </div>
    );
  }

  return (
    <div
      style={{
        background: '#f6f8fa',
        minHeight: '100vh',
        fontFamily:
          "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
        color: '#0b1220',
      }}
    >
      {/* ── Top bar (mirrors edit page) ── */}
      <div
        style={{
          background: '#fff',
          borderBottom: '1px solid #e2e8f0',
          padding: '14px 24px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 16,
          flexWrap: 'wrap',
          position: 'sticky',
          top: 0,
          zIndex: 50,
        }}
      >
        <div
          style={{ display: 'flex', alignItems: 'center', gap: 14, minWidth: 0, flex: 1 }}
        >
          <button onClick={() => router.back()} title="Back" style={btnStyle('secondary')}>
            <FiArrowLeft size={13} /> Back
          </button>
          <div style={{ minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
              <span
                style={{
                  fontSize: 9,
                  padding: '2px 7px',
                  background: '#15803d',
                  color: '#fff',
                  borderRadius: 4,
                  fontWeight: 700,
                  letterSpacing: '0.06em',
                }}
              >
                NEW
              </span>
              <span
                style={{
                  fontSize: 10,
                  color: '#94a3b8',
                  fontFamily: "'JetBrains Mono', monospace",
                }}
              >
                {ctx?.audit_code || `Audit #${auditId}`}
              </span>
            </div>
            <div style={{ fontSize: 14, fontWeight: 600, color: '#0b1220' }}>
              {loadingCtx ? 'Loading…' : ctx?.company_name || 'Raise new NC'}
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <button onClick={() => router.back()} style={btnStyle('secondary')}>
            Cancel
          </button>
          <button onClick={handleSubmit} disabled={saving} style={btnStyle('primary', saving)}>
            <FiSave size={13} />
            {saving ? 'Raising…' : 'Raise NC'}
          </button>
        </div>
      </div>

      {/* ── Main ── */}
      <div style={{ padding: '20px 24px 90px', maxWidth: 1280, margin: '0 auto' }}>
        {ctxError && (
          <div
            style={{
              marginBottom: 12,
              padding: '9px 13px',
              background: '#fffbeb',
              border: '1px solid #fde68a',
              borderRadius: 8,
              fontSize: 12,
              color: '#92400e',
            }}
          >
            {ctxError} — you can still raise the NC; company &amp; audit type are
            filled from the audit automatically.
          </div>
        )}

        {/* ═══ AUDIT CONTEXT (same as edit page) ═══ */}
        <SectionCard
          icon={<FiInfo size={14} color="#185FA5" />}
          iconBg="#E6F1FB"
          title="Audit context"
          subtitle="Company and audit type auto-fill from the audit; enter auditee, type, dates and notes"
          open={contextOpen}
          onToggle={() => setContextOpen((v) => !v)}
        >
          <div style={{ padding: '16px 18px' }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
              {/* Auto-filled (read-only) */}
              <Field label="Company" readOnly>
                <ReadOnlyValue value={loadingCtx ? 'Loading…' : ctx?.company_name || '— (from audit)'} />
              </Field>
              <Field label="Audit type" readOnly>
                <ReadOnlyValue value={loadingCtx ? 'Loading…' : ctx?.audit_type || auditType || '— (from audit)'} />
              </Field>

              <Field label="Auditee name">
                <input
                  value={auditeeName}
                  onChange={(e) => setAuditeeName(e.target.value)}
                  style={inputStyle()}
                  placeholder="Name - Designation, Name2 - Designation"
                />
              </Field>
              <Field label="Overall NC type">
                <select value={ncType} onChange={(e) => setNcType(e.target.value)} style={inputStyle()}>
                  <option value="Major">Major</option>
                  <option value="Minor">Minor</option>
                  <option value="Observation">Observation</option>
                </select>
              </Field>

              <Field label="Follow-up date">
                <input type="date" value={followUpDate} onChange={(e) => setFollowUpDate(e.target.value)} style={inputStyle()} />
              </Field>
              <Field label="Due date">
                <input type="date" value={dueDate} onChange={(e) => setDueDate(e.target.value)} style={inputStyle()} />
              </Field>

              <div style={{ gridColumn: 'span 2' }}>
                <Field label="Follow-up notes">
                  <textarea
                    value={followUpNotes}
                    onChange={(e) => setFollowUpNotes(e.target.value)}
                    placeholder="Add any follow-up information or actions taken"
                    rows={3}
                    style={{ ...inputStyle(), height: 'auto', paddingTop: 9, fontFamily: 'inherit', resize: 'vertical', lineHeight: 1.5 }}
                  />
                </Field>
              </div>

              <div style={{ gridColumn: 'span 2' }}>
                <Field label="Remark (NC-level)">
                  <textarea
                    value={remark}
                    onChange={(e) => setRemark(e.target.value)}
                    placeholder="Overall remark for this NC"
                    rows={2}
                    style={{ ...inputStyle(), height: 'auto', paddingTop: 9, fontFamily: 'inherit', resize: 'vertical', lineHeight: 1.5 }}
                  />
                </Field>
              </div>
            </div>
          </div>
        </SectionCard>

        {/* ═══ RAISED FINDINGS ═══ */}
        <div
          style={{
            background: '#fff',
            border: '1px solid #e2e8f0',
            borderRadius: 12,
            marginBottom: 12,
            overflow: 'hidden',
          }}
        >
          {/* header */}
          <div
            style={{
              padding: '13px 18px',
              borderBottom: '1px solid #e2e8f0',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
              <div
                style={{
                  width: 28,
                  height: 28,
                  background: '#FAEEDA',
                  borderRadius: 7,
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
              >
                <FiList size={14} color="#854F0B" />
              </div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: '#0b1220' }}>
                  Raised NC findings · {findings.length}
                </div>
                <div style={{ fontSize: 10, color: '#94a3b8', marginTop: 1 }}>
                  Each finding becomes one NCR entry on this NC
                </div>
              </div>
            </div>
          </div>

          {/* finding list */}
          <div style={{ padding: '16px 18px', display: 'flex', flexDirection: 'column', gap: 12 }}>
            {findings.map((f, i) => (
              <div
                key={i}
                style={{
                  border: '1px solid #e2e8f0',
                  borderLeft: '3px solid #854F0B',
                  borderRadius: 10,
                  padding: 14,
                  background: '#fafbfc',
                }}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                  <span style={{ fontSize: 12, fontWeight: 700, color: '#0b1220' }}>
                    Finding #{i + 1}
                  </span>
                  {findings.length > 1 && (
                    <button onClick={() => removeFinding(i)} style={removeBtn}>
                      <FiTrash2 size={11} /> Remove
                    </button>
                  )}
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
                  <div style={{ gridColumn: 'span 2' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5 }}>
                      <div
                        style={{
                          fontSize: 10,
                          fontWeight: 700,
                          color: '#64748b',
                          textTransform: 'uppercase',
                          letterSpacing: '0.08em',
                        }}
                      >
                        NCR statement *
                      </div>
                      <button
                        onClick={() => handleAiDraft(i)}
                        disabled={draftingIndex === i}
                        style={{
                          background: draftingIndex === i ? '#cbd5e1' : '#185FA5',
                          color: '#fff',
                          border: 'none',
                          borderRadius: 6,
                          padding: '3px 9px',
                          fontSize: 10,
                          fontWeight: 700,
                          cursor: draftingIndex === i ? 'wait' : 'pointer',
                          display: 'inline-flex',
                          alignItems: 'center',
                          gap: 4,
                          letterSpacing: '0.02em',
                        }}
                        title="Type a few words above, then click to draft"
                      >
                        {draftingIndex === i ? 'Drafting…' : '✨ Draft with AI'}
                      </button>
                    </div>
                      <textarea
                        value={f.ncr_statement}
                        onChange={(e) => updateFinding(i, { ncr_statement: e.target.value })}
                        rows={2}
                        style={{ ...inputStyle(), height: 'auto', paddingTop: 9, resize: 'vertical', fontFamily: 'inherit', lineHeight: 1.5 }}
                        placeholder="Describe the non-conformity finding…"
                      />
                    
                  </div>

                  <Field label="Criteria / clause">
                    <input
                      value={f.criteria_clause}
                      onChange={(e) => updateFinding(i, { criteria_clause: e.target.value })}
                      style={inputStyle()}
                      placeholder="e.g. Clause 8.5.1"
                    />
                  </Field>
                  <Field label="Finding NC type">
                    <select value={f.nc_type} onChange={(e) => updateFinding(i, { nc_type: e.target.value })} style={inputStyle()}>
                      <option value="">(same as NC)</option>
                      <option value="Major">Major</option>
                      <option value="Minor">Minor</option>
                      <option value="Observation">Observation</option>
                    </select>
                  </Field>

                  <div style={{ gridColumn: 'span 2' }}>
                    <Field label="Corrective action (optional)">
                      <textarea
                        value={f.corrective_action}
                        onChange={(e) => updateFinding(i, { corrective_action: e.target.value })}
                        rows={2}
                        style={{ ...inputStyle(), height: 'auto', paddingTop: 9, resize: 'vertical', fontFamily: 'inherit', lineHeight: 1.5 }}
                        placeholder="Proposed corrective action…"
                      />
                    </Field>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* Add more button (mirrors edit page's "Add more NC items") */}
          <button
            onClick={addFinding}
            style={{
              width: '100%',
              padding: '12px 13px',
              background: '#fafbfc',
              border: 'none',
              borderTop: '1px solid #e2e8f0',
              color: '#185FA5',
              fontSize: 12,
              fontWeight: 700,
              cursor: 'pointer',
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 6,
              letterSpacing: '0.02em',
            }}
          >
            <FiPlus size={14} /> Add more NC items
          </button>
        </div>

        {/* footer actions */}
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 4 }}>
          <button onClick={() => router.back()} style={btnStyle('secondary')}>Cancel</button>
          <button onClick={handleSubmit} disabled={saving} style={btnStyle('primary', saving)}>
            <FiSave size={13} /> {saving ? 'Raising…' : 'Raise NC'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// Helpers (same visual language as the edit page)
// ═══════════════════════════════════════════════════════════════════════

function SectionCard({
  icon,
  iconBg = '#f1f5f9',
  title,
  subtitle,
  open,
  onToggle,
  children,
}: {
  icon: React.ReactNode;
  iconBg?: string;
  title: string;
  subtitle?: string;
  open: boolean;
  onToggle: () => void;
  children: React.ReactNode;
}) {
  return (
    <div
      style={{
        background: '#fff',
        border: '1px solid #e2e8f0',
        borderRadius: 12,
        marginBottom: 12,
        overflow: 'hidden',
      }}
    >
      <button
        onClick={onToggle}
        style={{
          width: '100%',
          padding: '13px 18px',
          background: 'transparent',
          border: 'none',
          borderBottom: open ? '1px solid #e2e8f0' : 'none',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          cursor: 'pointer',
          textAlign: 'left',
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
          <div
            style={{
              width: 28,
              height: 28,
              background: iconBg,
              borderRadius: 7,
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            {icon}
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 600, color: '#0b1220' }}>{title}</div>
            {subtitle && (
              <div style={{ fontSize: 10, color: '#94a3b8', marginTop: 1 }}>{subtitle}</div>
            )}
          </div>
        </div>
        <FiChevronDown
          size={14}
          color="#94a3b8"
          style={{ transform: open ? 'none' : 'rotate(-90deg)', transition: 'transform 0.15s' }}
        />
      </button>
      {open && children}
    </div>
  );
}

function Field({
  label,
  readOnly,
  children,
}: {
  label: string;
  readOnly?: boolean;
  children: React.ReactNode;
}) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 5 }}>
        <div
          style={{
            fontSize: 10,
            fontWeight: 700,
            color: '#64748b',
            textTransform: 'uppercase',
            letterSpacing: '0.08em',
          }}
        >
          {label}
        </div>
        {readOnly && (
          <span
            style={{
              fontSize: 8,
              padding: '1px 5px',
              background: '#f1f5f9',
              color: '#94a3b8',
              borderRadius: 4,
              fontWeight: 700,
              letterSpacing: '0.04em',
            }}
          >
            AUTO
          </span>
        )}
      </div>
      {children}
    </div>
  );
}

function ReadOnlyValue({ value }: { value: string }) {
  return (
    <div
      style={{
        width: '100%',
        background: '#fafbfc',
        border: '1px solid #f1f5f9',
        borderRadius: 7,
        padding: '8px 11px',
        fontSize: 13,
        fontWeight: 500,
        color: '#475569',
        height: 36,
        display: 'flex',
        alignItems: 'center',
        boxSizing: 'border-box',
      }}
    >
      {value}
    </div>
  );
}

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

function btnStyle(variant: 'primary' | 'secondary', disabled = false): React.CSSProperties {
  if (variant === 'primary') {
    return {
      background: '#0b1220',
      color: '#fff',
      border: 'none',
      padding: '7px 14px',
      borderRadius: 7,
      fontSize: 11,
      fontWeight: 600,
      cursor: disabled ? 'wait' : 'pointer',
      display: 'inline-flex',
      alignItems: 'center',
      gap: 5,
      opacity: disabled ? 0.7 : 1,
      letterSpacing: '0.01em',
    };
  }
  return {
    background: '#fff',
    color: '#475569',
    border: '1px solid #e2e8f0',
    padding: '7px 12px',
    borderRadius: 7,
    fontSize: 11,
    fontWeight: 500,
    cursor: 'pointer',
    display: 'inline-flex',
    alignItems: 'center',
    gap: 5,
    letterSpacing: '0.01em',
  };
}

const removeBtn: React.CSSProperties = {
  display: 'inline-flex',
  alignItems: 'center',
  gap: 4,
  padding: '3px 8px',
  background: '#fef2f2',
  border: '1px solid #fca5a5',
  color: '#b91c1c',
  borderRadius: 6,
  fontSize: 11,
  fontWeight: 600,
  cursor: 'pointer',
};