'use client';

import React, { useState } from 'react';
import {
  FiMail,
  FiInfo,
  FiUsers,
  FiUser,
  FiChevronDown,
  FiChevronRight,
} from 'react-icons/fi';

// ═══════════════════════════════════════════════════════════════════════
// EmailNotificationsPanel — email triggers (Phase 2 wiring pending)
// ═══════════════════════════════════════════════════════════════════════
// Matches the legacy CRM's email flow:
//   1. Send NC Doc to Client/Coordinator  →  To, CC, BCC (multi-recipient)
//   2. Send Uploaded NC Doc to Coordinator/Auditor  →  Auditor + Coordinator emails
//
// Multi-recipient: separate addresses with commas.
// Currently UI-only — backend wiring comes in Phase 2.
// ═══════════════════════════════════════════════════════════════════════

export interface EmailPrefs {
  send_nc_to_client: boolean;
  client_to: string;
  client_cc: string;
  client_bcc: string;
  send_to_coord_auditor: boolean;
  auditor_email: string;
  coordinator_email: string;
}

export const defaultEmailPrefs: EmailPrefs = {
  send_nc_to_client: false,
  client_to: '',
  client_cc: '',
  client_bcc: '',
  send_to_coord_auditor: false,
  auditor_email: '',
  coordinator_email: '',
};

interface Props {
  value: EmailPrefs;
  onChange: (patch: Partial<EmailPrefs>) => void;
  onSend?: () => void;        // 🆕
  sending?: boolean;          // 🆕
}

export default function EmailNotificationsPanel({ value, onChange, onSend, sending }: Props) {
  const [open, setOpen] = useState(true);
  const activeCount =
    (value.send_nc_to_client ? 1 : 0) +
    (value.send_to_coord_auditor ? 1 : 0);

  return (
    <div
      style={{
        background: '#fff',
        border: '1px solid #e2e8f0',
        borderRadius: 12,
        overflow: 'hidden',
        marginBottom: 12,
      }}
    >
      {/* Header */}
      <button
        onClick={() => setOpen((v) => !v)}
        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: 10 }}>
          <div
            style={{
              width: 28,
              height: 28,
              background: '#eef2ff',
              borderRadius: 7,
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <FiMail size={14} color="#4338ca" />
          </div>
          <div>
            <div
              style={{
                fontSize: 13,
                fontWeight: 600,
                color: '#0b1220',
                display: 'flex',
                alignItems: 'center',
                gap: 8,
              }}
            >
              Email notifications
              {activeCount > 0 && (
                <span
                  style={{
                    fontSize: 9,
                    padding: '2px 7px',
                    background: '#eef2ff',
                    color: '#4338ca',
                    borderRadius: 99,
                    fontWeight: 700,
                    letterSpacing: '0.04em',
                  }}
                >
                  {activeCount} ACTIVE
                </span>
              )}
            </div>
            <div style={{ fontSize: 10, color: '#94a3b8', marginTop: 1 }}>
              Configure who receives the NC document and uploaded report
            </div>
          </div>
        </div>
        {open ? (
          <FiChevronDown size={14} color="#94a3b8" />
        ) : (
          <FiChevronRight size={14} color="#94a3b8" />
        )}
      </button>

      {open && (
        <div style={{ padding: '16px 18px 18px' }}>
          {/* Send action */}
          {onSend && (
            <div
              style={{
                display: 'flex',
                justifyContent: 'flex-end',
                marginBottom: 16,
              }}
            >
              <button
                onClick={onSend}
                disabled={
                  sending ||
                  (!value.send_nc_to_client && !value.send_to_coord_auditor)
                }
                style={{
                  padding: '9px 18px',
                  background: sending ? '#94a3b8' : '#185FA5',
                  color: '#fff',
                  border: 'none',
                  borderRadius: 8,
                  fontSize: 12,
                  fontWeight: 700,
                  cursor: sending ? 'wait' : 'pointer',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 6,
                  opacity:
                    !value.send_nc_to_client && !value.send_to_coord_auditor
                      ? 0.5
                      : 1,
                }}
              >
                <FiMail size={13} />
                {sending ? 'Sending…' : 'Send now'}
              </button>
            </div>
          )}

          {/* Trigger 1: NC to Client/Coordinator */}
          <Trigger
            id="trig-client"
            icon={<FiUsers size={14} color="#185FA5" />}
            iconBg="#E6F1FB"
            title="Send NC Doc to Client / Coordinator"
            subtitle="Sends the system-generated NC document via email"
            checked={value.send_nc_to_client}
            onToggle={(v) => onChange({ send_nc_to_client: v })}
          >
            <div
              style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(3, 1fr)',
                gap: 12,
              }}
            >
              <EmailField
                label="To (Client email)"
                value={value.client_to}
                onChange={(v) => onChange({ client_to: v })}
                placeholder="client@example.com"
                required
              />
              <EmailField
                label="CC"
                value={value.client_cc}
                onChange={(v) => onChange({ client_cc: v })}
                placeholder="cc@example.com"
              />
              <EmailField
                label="BCC"
                value={value.client_bcc}
                onChange={(v) => onChange({ client_bcc: v })}
                placeholder="bcc@example.com"
              />
            </div>
            <Hint />
          </Trigger>

          {/* Trigger 2: Uploaded NC to Coordinator/Auditor */}
          <Trigger
            id="trig-coord"
            icon={<FiUser size={14} color="#0F6E56" />}
            iconBg="#E1F5EE"
            title="Send Uploaded NC Doc to Coordinator / Auditor"
            subtitle="Sends the most recent uploaded evidence to internal team"
            checked={value.send_to_coord_auditor}
            onToggle={(v) => onChange({ send_to_coord_auditor: v })}
          >
            <div
              style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(2, 1fr)',
                gap: 12,
              }}
            >
              <EmailField
                label="Auditor email"
                value={value.auditor_email}
                onChange={(v) => onChange({ auditor_email: v })}
                placeholder="auditor@example.com"
              />
              <EmailField
                label="Coordinator email"
                value={value.coordinator_email}
                onChange={(v) => onChange({ coordinator_email: v })}
                placeholder="coordinator@example.com"
              />
            </div>
            <Hint />
          </Trigger>
        </div>
      )}
    </div>
  );
}

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

function Trigger({
  id,
  icon,
  iconBg,
  title,
  subtitle,
  checked,
  onToggle,
  children,
}: {
  id: string;
  icon: React.ReactNode;
  iconBg: string;
  title: string;
  subtitle: string;
  checked: boolean;
  onToggle: (v: boolean) => void;
  children: React.ReactNode;
}) {
  return (
    <div
      style={{
        background: checked ? '#fafbfc' : 'transparent',
        border: '1px solid',
        borderColor: checked ? '#cbd5e1' : '#e2e8f0',
        borderRadius: 10,
        padding: '14px 16px',
        marginBottom: 12,
        transition: 'all 0.15s',
      }}
    >
      <label
        htmlFor={id}
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 11,
          cursor: 'pointer',
          marginBottom: checked ? 14 : 0,
        }}
      >
        {/* Custom checkbox visual */}
        <span
          style={{
            position: 'relative',
            display: 'inline-flex',
            alignItems: 'center',
            justifyContent: 'center',
            width: 18,
            height: 18,
            background: checked ? '#185FA5' : '#fff',
            border: `1.5px solid ${checked ? '#185FA5' : '#cbd5e1'}`,
            borderRadius: 4,
            flexShrink: 0,
            transition: 'all 0.12s',
          }}
        >
          {checked && (
            <svg
              width="10"
              height="10"
              viewBox="0 0 12 12"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M2 6L5 9L10 3"
                stroke="white"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          )}
        </span>
        <input
          id={id}
          type="checkbox"
          checked={checked}
          onChange={(e) => onToggle(e.target.checked)}
          style={{
            position: 'absolute',
            opacity: 0,
            pointerEvents: 'none',
            width: 0,
            height: 0,
          }}
        />
        <div
          style={{
            display: 'inline-flex',
            alignItems: 'center',
            justifyContent: 'center',
            width: 30,
            height: 30,
            background: iconBg,
            borderRadius: 7,
            flexShrink: 0,
          }}
        >
          {icon}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div
            style={{
              fontSize: 12,
              fontWeight: 600,
              color: '#0b1220',
              marginBottom: 1,
            }}
          >
            {title}
          </div>
          <div style={{ fontSize: 10, color: '#64748b' }}>{subtitle}</div>
        </div>
      </label>

      {checked && (
        <div style={{ paddingLeft: 29 }}>{children}</div>
      )}
    </div>
  );
}

function EmailField({
  label,
  value,
  onChange,
  placeholder,
  required,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  placeholder: string;
  required?: boolean;
}) {
  return (
    <div>
      <div
        style={{
          fontSize: 9,
          fontWeight: 700,
          color: '#64748b',
          textTransform: 'uppercase',
          letterSpacing: '0.08em',
          marginBottom: 4,
        }}
      >
        {label} {required && <span style={{ color: '#dc2626' }}>*</span>}
      </div>
      <input
        type="text"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        style={{
          width: '100%',
          padding: '7px 10px',
          fontSize: 12,
          border: '1px solid #e2e8f0',
          borderRadius: 6,
          background: '#fff',
          color: '#0b1220',
          outline: 'none',
          boxSizing: 'border-box',
          fontFamily: 'inherit',
        }}
      />
    </div>
  );
}

function Hint() {
  return (
    <div
      style={{
        fontSize: 10,
        color: '#94a3b8',
        marginTop: 8,
        display: 'inline-flex',
        alignItems: 'center',
        gap: 5,
      }}
    >
      <FiInfo size={10} /> Separate multiple recipients with a comma (e.g.{' '}
      <span style={{ fontFamily: "'JetBrains Mono', monospace" }}>
        a@x.com, b@x.com
      </span>
      )
    </div>
  );
}
