/**
 * Compose modal — rich text editor (TipTap) with template insert.
 * Used for new mail, reply, and forward.
 */

import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Modal } from '@/components/ui/Modal';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Select } from '@/components/ui/Select';
import { TemplatePicker } from './TemplatePicker';
import { RichTextEditor } from './RichTextEditor';
import type { Mail, MailSignature, SendMailPayload, ReplyPayload, ForwardPayload, MailDraftPayload } from '@/api/mail';
import { uploadAttachment, type UploadedAttachment, replaceSignatureVariables } from '@/api/mail';
import { useAuthStore } from '@/store/authStore';

export type ComposeMode = 'new' | 'reply' | 'forward' | 'draft';

export interface ComposeModalProps {
  open: boolean;
  mode: ComposeMode;
  accountId: string;
  replyToMail: Mail | null;
  forwardMail: Mail | null;
  draftMail?: Mail | null;
  signatures: MailSignature[];
  onSend: (payload: SendMailPayload | ReplyPayload | ForwardPayload, mode: ComposeMode) => Promise<void>;
  onSaveDraft?: (payload: MailDraftPayload) => Promise<void>;
  onClose: () => void;
}

export function ComposeModal({
  open,
  mode,
  accountId,
  replyToMail,
  forwardMail,
  draftMail,
  signatures,
  onSend,
  onSaveDraft,
  onClose,
}: ComposeModalProps) {
  const { t } = useTranslation();
  const authUser = useAuthStore((s) => s.user);
  const authTenant = useAuthStore((s) => s.currentTenant);
  const [to, setTo] = useState('');
  const [cc, setCc] = useState('');
  const [bcc, setBcc] = useState('');
  const [subject, setSubject] = useState('');
  const [body, setBody] = useState('');
  const [showCc, setShowCc] = useState(false);
  const [sending, setSending] = useState(false);
  const [savingDraft, setSavingDraft] = useState(false);
  const [selectedSignatureId, setSelectedSignatureId] = useState('');
  const [showTemplatePicker, setShowTemplatePicker] = useState(false);
  const [attachments, setAttachments] = useState<UploadedAttachment[]>([]);
  const [uploadingFile, setUploadingFile] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!open) return;
    if (mode === 'reply' && replyToMail) {
      setTo(replyToMail.from_address);
      setSubject(replyToMail.subject.startsWith('Re: ') ? replyToMail.subject : `Re: ${replyToMail.subject}`);
      setBody(`\n\n---\n${replyToMail.body_text.slice(0, 200)}`);
    } else if (mode === 'forward' && forwardMail) {
      setTo('');
      setSubject(forwardMail.subject.startsWith('Fwd: ') ? forwardMail.subject : `Fwd: ${forwardMail.subject}`);
      setBody(`\n\n---\n${t('mail.forwarding')}\n${t('mail.from')}: ${forwardMail.from_address}\n${t('mail.subject')}: ${forwardMail.subject}\n\n${forwardMail.body_text.slice(0, 200)}`);
    } else if (mode === 'draft' && draftMail) {
      setTo(draftMail.to_addresses.join(', '));
      setCc(draftMail.cc_addresses.join(', '));
      setBcc(draftMail.bcc_addresses.join(', '));
      setSubject(draftMail.subject);
      setBody(draftMail.body_html || draftMail.body_text || '');
      setShowCc(draftMail.cc_addresses.length > 0 || draftMail.bcc_addresses.length > 0);
    } else {
      setTo('');
      setCc('');
      setBcc('');
      setSubject('');
      setBody('');
      setAttachments([]);
    }
  }, [open, mode, replyToMail, forwardMail, draftMail, t]);

  const insertSignature = useCallback((signatureId: string) => {
    setSelectedSignatureId(signatureId);
    const sig = signatures.find((s) => s.id === signatureId);
    if (sig) {
      const processedHtml = replaceSignatureVariables(
        sig.body_html,
        { name: authUser ? `${authUser.first_name} ${authUser.last_name}`.trim() : undefined, email: authUser?.email, role: authUser?.role, first_name: authUser?.first_name, last_name: authUser?.last_name },
        { name: authTenant?.name },
      );
      setBody((prev) => `${prev}<br/><br/>---<br/>${processedHtml}`);
    }
  }, [signatures, authUser, authTenant]);

  const handleTemplateSelect = useCallback((templateBody: string, templateSubject: string) => {
    setBody(templateBody);
    if (templateSubject) {
      setSubject(templateSubject);
    }
    setShowTemplatePicker(false);
  }, []);

  const handleFileSelect = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;
    setUploadingFile(true);
    try {
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        if (file.size > 25 * 1024 * 1024) {
          alert(`${file.name} exceeds 25 MB limit`);
          continue;
        }
        const uploaded = await uploadAttachment(file);
        setAttachments((prev) => [...prev, uploaded]);
      }
    } catch (err) {
      console.error('Attachment upload failed:', err);
      alert('Failed to upload attachment');
    } finally {
      setUploadingFile(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  }, []);

  const handleRemoveAttachment = useCallback((attId: string) => {
    setAttachments((prev) => prev.filter((a) => a.id !== attId));
  }, []);

  const formatBytes = (bytes: number): string => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  const handleSaveDraft = useCallback(async () => {
    if (!onSaveDraft) return;
    setSavingDraft(true);
    try {
      const toList = to.split(',').map((s) => s.trim()).filter(Boolean);
      const ccList = cc ? cc.split(',').map((s) => s.trim()).filter(Boolean) : [];
      const bccList = bcc ? bcc.split(',').map((s) => s.trim()).filter(Boolean) : [];
      const payload: MailDraftPayload = {
        account_id: accountId,
        to: toList,
        cc: ccList,
        bcc: bccList,
        subject,
        body_text: body.replace(/<[^>]*>/g, ''),
        body_html: body,
      };
      await onSaveDraft(payload);
    } finally {
      setSavingDraft(false);
    }
  }, [to, cc, bcc, subject, body, accountId, onSaveDraft]);

  const handleSend = useCallback(async () => {
    if (!to.trim()) return;
    setSending(true);
    try {
      const toList = to.split(',').map((s) => s.trim()).filter(Boolean);
      const ccList = cc ? cc.split(',').map((s) => s.trim()).filter(Boolean) : undefined;
      const bccList = bcc ? bcc.split(',').map((s) => s.trim()).filter(Boolean) : undefined;

      if (mode === 'reply' && replyToMail) {
        const replyPayload: ReplyPayload = {
          account_id: accountId,
          body,
          is_html: true,
          to: toList,
          cc: ccList,
          signature_id: selectedSignatureId || null,
        };
        await onSend(replyPayload, 'reply');
      } else if (mode === 'forward' && forwardMail) {
        const fwdPayload: ForwardPayload = {
          account_id: accountId,
          to: toList,
          body,
          is_html: true,
          signature_id: selectedSignatureId || null,
        };
        await onSend(fwdPayload, 'forward');
      } else {
        const sendPayload: SendMailPayload = {
          account_id: accountId,
          to: toList,
          cc: ccList,
          bcc: bccList,
          subject,
          body,
          is_html: true,
          signature_id: selectedSignatureId || null,
          attachments: attachments.map((a) => a.id),
        };
        await onSend(sendPayload, 'new');
      }
      setAttachments([]);
      onClose();
    } finally {
      setSending(false);
    }
  }, [to, cc, bcc, subject, body, mode, replyToMail, forwardMail, accountId, selectedSignatureId, attachments, onSend, onClose]);

  const title = mode === 'reply' ? t('mail.reply') : mode === 'forward' ? t('mail.forward') : mode === 'draft' ? t('mail.editDraft') : t('mail.compose');

  return (
    <Modal open={open} onClose={onClose} title={title} size="xl" closeOnBackdrop={false} fullScreenMobile>
      <div className="space-y-4" data-testid="compose-modal">
        {/* Template picker toggle (formatting toolbar is in RichTextEditor) */}
        <div className="flex items-center gap-2" data-testid="compose-toolbar">
          <button
            onClick={() => setShowTemplatePicker(!showTemplatePicker)}
            className="px-3 py-1.5 rounded hover:bg-secondary-100 text-sm"
            aria-label={t('mail.insertTemplate')}
            title={t('mail.insertTemplate')}
            type="button"
            data-testid="template-picker-toggle"
          >
            {t('mail.template')}
          </button>
        </div>

        {showTemplatePicker && (
          <TemplatePicker onSelect={handleTemplateSelect} />
        )}

        {/* Recipients */}
        <div className="space-y-2">
          <Input
            label={t('mail.to')}
            value={to}
            onChange={(e) => setTo(e.target.value)}
            placeholder="recipient@example.com"
            required
            data-testid="compose-to"
          />
          <div className="flex items-center gap-2">
            {!showCc ? (
              <button
                onClick={() => setShowCc(true)}
                className="text-sm text-primary-600 hover:text-primary-700"
                type="button"
              >
                {t('mail.showCcBcc')}
              </button>
            ) : (
              <div className="w-full grid grid-cols-1 sm:grid-cols-2 gap-2">
                <Input
                  label={t('mail.cc')}
                  value={cc}
                  onChange={(e) => setCc(e.target.value)}
                  placeholder="cc@example.com"
                />
                <Input
                  label={t('mail.bcc')}
                  value={bcc}
                  onChange={(e) => setBcc(e.target.value)}
                  placeholder="bcc@example.com"
                />
              </div>
            )}
          </div>
          <Input
            label={t('mail.subject')}
            value={subject}
            onChange={(e) => setSubject(e.target.value)}
            placeholder={t('mail.subjectPlaceholder')}
            data-testid="compose-subject"
          />
        </div>

        {/* Editor */}
        <div>
          <label className="block text-sm font-medium text-secondary-700 mb-1">{t('mail.body')}</label>
          <RichTextEditor
            content={body}
            onChange={setBody}
            placeholder={t('mail.body')}
          />
        </div>

        {/* Attachments */}
        <div data-testid="compose-attachments">
          <label className="block text-sm font-medium text-secondary-700 mb-1">{t('mail.attachments')}</label>
          <div className="flex items-center gap-2">
            <input
              ref={fileInputRef}
              type="file"
              multiple
              onChange={handleFileSelect}
              className="hidden"
              data-testid="compose-file-input"
            />
            <Button
              variant="secondary"
              size="sm"
              type="button"
              onClick={() => fileInputRef.current?.click()}
              isLoading={uploadingFile}
              icon={
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
                </svg>
              }
            >
              {t('mail.addAttachment')}
            </Button>
            <span className="text-xs text-secondary-400">Max 25 MB per file</span>
          </div>
          {attachments.length > 0 && (
            <ul className="mt-2 space-y-1">
              {attachments.map((att) => (
                <li key={att.id} className="flex items-center gap-3 p-2 rounded-md bg-secondary-50">
                  <svg className="w-5 h-5 text-secondary-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                  </svg>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm text-secondary-800 truncate">{att.filename}</p>
                    <p className="text-xs text-secondary-400">{formatBytes(att.size_bytes)}</p>
                  </div>
                  <button
                    type="button"
                    onClick={() => handleRemoveAttachment(att.id)}
                    className="p-1 rounded hover:bg-secondary-200 text-secondary-500"
                    aria-label={t('common.remove')}
                  >
                    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </button>
                </li>
              ))}
            </ul>
          )}
        </div>

        {/* Signature */}
        <Select
          label={t('mail.signature')}
          value={selectedSignatureId}
          onChange={(e) => insertSignature(e.target.value)}
          options={[
            { value: '', label: t('mail.noSignature') },
            ...signatures.map((sig) => ({ value: sig.id, label: sig.name })),
          ]}
        />

        {/* Actions */}
        <div className="flex justify-end gap-2 pt-2 border-t border-secondary-200 sticky bottom-0 bg-white py-3">
          <Button variant="secondary" onClick={onClose} type="button">
            {t('common.cancel')}
          </Button>
          {onSaveDraft && (
            <Button
              variant="secondary"
              onClick={handleSaveDraft}
              isLoading={savingDraft}
              type="button"
              data-testid="compose-save-draft"
            >
              {t('mail.saveDraft')}
            </Button>
          )}
          <Button onClick={handleSend} isLoading={sending} type="button" data-testid="compose-send">
            {t('mail.send')}
          </Button>
        </div>
      </div>
    </Modal>
  );
}