'use client';

import React, { useState, useCallback } from 'react';
import { FiPlus, FiX, FiInfo } from 'react-icons/fi';
import type { EditableEntry } from './findings.types';

// ═══════════════════════════════════════════════════════════════════════
// AddFindingPanel — inline form to add a new NC item
// ═══════════════════════════════════════════════════════════════════════
// Note: backend support for adding new findings comes in Phase 2.
// For now, "Add to list" creates a client-side draft (id = negative number).
// Drafts show in the sidebar with a DRAFT badge and can be fully edited,
// but won't persist until the backend endpoint is wired up.
// ═══════════════════════════════════════════════════════════════════════

interface Props {
  onAdd: (draft: Omit<EditableEntry, 'id' | '_dirty'>) => void;
  onCancel: () => void;
}

type FormState = {
  nc_type: string;
  ncr_statement: string;
  criteria_clause: string;
  corrective_action: string;
  status: 'open' | 'closed' | 'pending';
  document_path: string | null;
};

const DEFAULTS: FormState = {
  nc_type: 'Minor',
  ncr_statement: '',
  criteria_clause: '',
  corrective_action: '',
  status: 'open',
  document_path: null,
};

export default function AddFindingPanel({ onAdd, onCancel }: Props) {
  const [form, setForm] = useState<FormState>(DEFAULTS);
  const [drafting, setDrafting] = useState(false);
  // Shows a brief confirmation after "Add to list" / "Add & New" so it's
  // clear to the user that the (now empty) form is intentionally ready
  // for the next entry, not stuck/broken.
  const [justAdded, setJustAdded] = 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 = form.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: form.nc_type || '', 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');
      setForm((prev) => ({
        ...prev,
        ncr_statement: d.statement || prev.ncr_statement,
        criteria_clause: d.clause || prev.criteria_clause,
        corrective_action: d.corrective_action || prev.corrective_action,
        nc_type: d.nc_type || prev.nc_type,
      }));
    } catch (e: any) {
      alert(e?.message || 'AI draft failed');
    } finally {
      setDrafting(false);
    }
  };
  const update = useCallback(
    <K extends keyof FormState>(key: K, val: FormState[K]) => {
      setForm((prev) => ({ ...prev, [key]: val }));
    },
    [],
  );

  const handleAdd = () => {
    if (!form.ncr_statement.trim()) {
      alert('Please enter the NCR statement');
      return;
    }
    onAdd({ ...form });
    setForm(DEFAULTS);
    // Let the user know the reset is intentional and the panel is ready
    // for another entry — no need to go back to the sidebar.
    setJustAdded(true);
    window.setTimeout(() => setJustAdded(false), 2200);
  };

  return (
    <div
      style={{
        background: '#fff',
        border: '1px solid #185FA5',
        borderRadius: 12,
        padding: 0,
        marginBottom: 14,
        overflow: 'hidden',
      }}
    >
      {/* Header */}
      <div
        style={{
          padding: '13px 18px',
          borderBottom: '1px solid #e2e8f0',
          background: '#f8faff',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div
            style={{
              width: 28,
              height: 28,
              background: '#185FA5',
              borderRadius: 7,
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <FiPlus size={14} color="#fff" />
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 600, color: '#0b1220' }}>
              Add new finding
            </div>
            <div style={{ fontSize: 10, color: '#64748b', marginTop: 1 }}>
              Fill in the details below and click <strong>Add to list</strong>
            </div>
          </div>
        </div>
        {/* Always-visible actions — lets the user add another item straight
            from here, without scrolling down the sidebar list. */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <button
            onClick={handleAdd}
            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,
            }}
            title="Add this item, then start a fresh one right here"
          >
            <FiPlus size={11} /> Add &amp; New
          </button>
          <button
            onClick={onCancel}
            style={{
              background: '#fff',
              border: '1px solid #e2e8f0',
              borderRadius: 6,
              padding: '5px 9px',
              color: '#64748b',
              cursor: 'pointer',
              fontSize: 11,
              fontWeight: 500,
              display: 'inline-flex',
              alignItems: 'center',
              gap: 4,
            }}
          >
            <FiX size={11} /> Cancel
          </button>
        </div>
      </div>

      {/* Form body */}
      <div style={{ padding: '16px 18px' }}>
        {justAdded && (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 6,
              fontSize: 11,
              fontWeight: 600,
              color: '#0F6E56',
              padding: '7px 10px',
              background: '#E1F5EE',
              border: '1px solid #b7e4d8',
              borderRadius: 6,
              marginBottom: 14,
            }}
          >
            <FiPlus size={11} /> Added! Form cleared — ready for your next finding.
          </div>
        )}

        {/* Type + Status */}
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: 14,
            marginBottom: 14,
          }}
        >
          <div>
            <Label>NC Type</Label>
            <Seg
              value={form.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) => update('nc_type', v)}
            />
          </div>
          <div>
            <Label>Status</Label>
            <Seg
              value={form.status}
              options={[
                { value: 'open', label: 'Open', color: '#A32D2D', bg: '#FCEBEB' },
                { value: 'pending', label: 'Pending', color: '#854F0B', bg: '#FAEEDA' },
                { value: 'closed', label: 'Closed', color: '#0F6E56', bg: '#E1F5EE' },
              ]}
              onChange={(v) =>
                update('status', v as 'open' | 'pending' | 'closed')
              }
            />
          </div>
        </div>

        {/* NCR statement */}
        <div style={{ marginBottom: 14 }}>
          <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 <span style={{ color: '#dc2626' }}>*</span>
            </div>
            <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 below, then click to draft"
            >
              {drafting ? 'Drafting…' : '✨ Draft with AI'}
            </button>
          </div>
          <textarea
            value={form.ncr_statement}
            onChange={(e) => update('ncr_statement', e.target.value)}
            placeholder="Describe the non-conformity finding observed during the audit…"
            rows={3}
            maxLength={1000}
            style={{
              ...inputStyle(),
              minHeight: 76,
              resize: 'vertical',
              lineHeight: 1.55,
            }}
          />
        </div>

        {/* Criteria + Corrective */}
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: 14,
            marginBottom: 16,
          }}
        >
          <div>
            <Label>Criteria clause</Label>
            <input
              value={form.criteria_clause}
              onChange={(e) => update('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={form.corrective_action}
              onChange={(e) => update('corrective_action', e.target.value)}
              placeholder="Auditee's proposed action"
              style={inputStyle()}
            />
          </div>
        </div>

        {/* Notice + Actions */}
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            paddingTop: 12,
            borderTop: '1px dashed #e2e8f0',
            gap: 12,
            flexWrap: 'wrap',
          }}
        >
          <div
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 6,
              fontSize: 11,
              color: '#92400e',
              padding: '5px 10px',
              background: '#fef3c7',
              border: '1px solid #fde68a',
              borderRadius: 6,
            }}
          >
            <FiInfo size={11} />
            Saved as draft until Phase 2 backend support
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            <button onClick={onCancel} style={btnSecondary()}>
              Cancel
            </button>
            <button onClick={handleAdd} style={btnPrimary()}>
              <FiPlus size={12} /> Add to list
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

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

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

function Seg({
  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 8px',
              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',
            }}
          >
            {opt.label}
          </button>
        );
      })}
    </div>
  );
}

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

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

function btnPrimary(): React.CSSProperties {
  return {
    background: '#185FA5',
    color: '#fff',
    border: 'none',
    padding: '7px 14px',
    borderRadius: 6,
    fontSize: 11,
    fontWeight: 600,
    cursor: 'pointer',
    display: 'inline-flex',
    alignItems: 'center',
    gap: 5,
  };
}

function btnSecondary(): React.CSSProperties {
  return {
    background: '#fff',
    color: '#475569',
    border: '1px solid #e2e8f0',
    padding: '7px 12px',
    borderRadius: 6,
    fontSize: 11,
    fontWeight: 500,
    cursor: 'pointer',
  };
}