"use client";

// 구매관리 > 발주서관리 — 메일 발송 다이얼로그
// EstimateMailDialog 패턴 1:1 (영업관리 견적관리) 발주서용 단순화:
//   - 공급업체(client_mng) 단일 email 자동 채움
//   - 단일 PDF 첨부 (호출자가 base64 미리 생성해서 props 로 전달)
//   - 발송 성공 시 purchase_order_master.mail_send_yn='Y'/mail_send_date=NOW()

import { useCallback, useEffect, useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Loader2, Send } from "lucide-react";
import { toast } from "sonner";
import { purchaseApi, PartnerManager } from "@/lib/api/purchase";

export interface PurchaseOrderMailDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  /** purchase_order_master.objid */
  pomObjid: string | null;
  /** form_type ('general' | 'outsourcing' | 'english') — 본문 템플릿 분기 */
  formType?: string;
  /** 호출자가 미리 생성한 발주서 PDF base64 (data URL 또는 raw) — 빈값이면 발송 단계에서 onRequestPdf 콜백 사용 */
  pdfBase64?: string;
  /** pdfBase64 가 없을 때 다이얼로그가 호출하는 PDF 생성기 (다이얼로그 외부 컴포넌트에서 DOM 캡처) */
  onRequestPdf?: () => Promise<string>;
  onSent?: () => void;
}

export function PurchaseOrderMailDialog({
  open,
  onOpenChange,
  pomObjid,
  formType = "general",
  pdfBase64,
  onRequestPdf,
  onSent,
}: PurchaseOrderMailDialogProps) {
  const isEnglish = formType === "english";

  const [loading, setLoading] = useState(false);
  const [sending, setSending] = useState(false);
  const [progress, setProgress] = useState("");
  const [managers, setManagers] = useState<PartnerManager[]>([]);
  const [checkedEmails, setCheckedEmails] = useState<Record<string, boolean>>({});
  const [form, setForm] = useState({
    toEmails: "",
    ccEmails: "",
    subject: "",
    contents: "",
  });

  useEffect(() => {
    if (!open || !pomObjid) return;
    let cancelled = false;
    (async () => {
      setLoading(true);
      setManagers([]);
      setCheckedEmails({});
      setForm({ toEmails: "", ccEmails: "", subject: "", contents: "" });
      try {
        const info = await purchaseApi.getOrderMailInfo(pomObjid);
        if (cancelled || !info) return;

        const partnerName = info.partner_name ?? "";
        const orderNo = info.purchase_order_no ?? "";
        const template = isEnglish
          ? `Dear ${partnerName},\n\n` +
            `Please find attached our Purchase Order (Ref. No: ${orderNo}).\n\n` +
            `Should you have any questions, please feel free to contact us.\n\n` +
            `Best regards,\nRPS CO., LTD.\n`
          : `안녕하세요.\n\n` +
            `${partnerName} 귀하께 발주서를 송부드립니다.\n\n` +
            `발주번호: ${orderNo}\n\n` +
            `첨부된 발주서를 확인하신 후 문의사항이 있으시면 연락 주시기 바랍니다.\n\n` +
            `감사합니다.\n`;

        setForm({
          toEmails: info.partner_email ?? "",
          ccEmails: info.writer_email ?? "",
          subject: isEnglish
            ? `[RPS] Purchase Order ${orderNo}`
            : `[${partnerName}] ${orderNo} 발주서`,
          contents: template,
        });

        if (info.partner_objid) {
          try {
            const mgrs = await purchaseApi.listPartnerManagers(info.partner_objid);
            if (!cancelled) setManagers(mgrs);
          } catch {/* skip */}
        }
      } catch (e: any) {
        toast.error("발주서 정보를 불러올 수 없습니다: " + (e?.message ?? ""));
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [open, pomObjid, isEnglish]);

  function toggleManager(email: string, checked: boolean) {
    setCheckedEmails((prev) => ({ ...prev, [email]: checked }));
    setForm((prev) => {
      const current = prev.toEmails.split(/[,;]/).map((e) => e.trim()).filter(Boolean);
      if (checked && !current.includes(email)) {
        return { ...prev, toEmails: current.concat(email).join(", ") };
      }
      if (!checked && current.includes(email)) {
        return { ...prev, toEmails: current.filter((e) => e !== email).join(", ") };
      }
      return prev;
    });
  }

  const handleSend = useCallback(async () => {
    if (!pomObjid) return;
    const toEmails = form.toEmails.trim();
    const subject = form.subject.trim();
    const contents = form.contents.trim();

    if (toEmails === "") { toast.error(isEnglish ? "Recipient required" : "수신인을 입력해주세요"); return; }
    if (subject === "")  { toast.error(isEnglish ? "Subject required"   : "제목을 입력해주세요"); return; }
    if (contents === "") { toast.error(isEnglish ? "Body required"      : "내용을 입력해주세요"); return; }

    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const emails = toEmails.split(/[,;]/).map((e) => e.trim()).filter(Boolean);
    for (const e of emails) {
      if (!emailPattern.test(e)) {
        toast.error(`올바른 이메일 형식이 아닙니다: ${e}`);
        return;
      }
    }

    if (!confirm(isEnglish ? "Send purchase order?" : "발주서를 발송하시겠습니까?")) return;

    setSending(true);
    setProgress(isEnglish ? "Preparing..." : "발송 준비 중...");
    try {
      let pdf = pdfBase64;
      if (!pdf && onRequestPdf) {
        setProgress(isEnglish ? "Generating PDF..." : "PDF 생성 중... (최대 30초)");
        pdf = await onRequestPdf();
      }
      if (!pdf) {
        toast.error(isEnglish ? "PDF not available" : "PDF 가 준비되지 않았습니다");
        setSending(false);
        setProgress("");
        return;
      }

      setProgress(isEnglish ? "Sending mail..." : "메일 발송 중...");
      const result = await purchaseApi.sendOrderMail({
        pomObjid,
        toEmails,
        ccEmails: form.ccEmails.trim() || undefined,
        subject,
        contents,
        pdfBase64: pdf,
      });

      if (!result.success) {
        toast.error((isEnglish ? "Send failed: " : "발송 실패: ") + result.message);
      } else {
        toast.success(result.message || (isEnglish ? "Sent" : "발주서가 발송되었습니다"));
        onOpenChange(false);
        onSent?.();
      }
    } catch (e: any) {
      toast.error((isEnglish ? "Send failed: " : "발송 실패: ") + (e?.response?.data?.message ?? e?.message ?? ""));
    } finally {
      setSending(false);
      setProgress("");
    }
  }, [pomObjid, form, isEnglish, pdfBase64, onRequestPdf, onOpenChange, onSent]);

  return (
    <Dialog open={open} onOpenChange={(o) => { if (!sending) onOpenChange(o); }}>
      <DialogContent className="max-w-3xl">
        <DialogHeader>
          <DialogTitle>{isEnglish ? "Send Purchase Order Email" : "발주서 메일 발송"}</DialogTitle>
          <DialogDescription>
            {isEnglish
              ? "Attachment: Purchase Order PDF (1 page)"
              : "PDF 첨부: 발주서 양식 1장"}
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <div className="flex items-center justify-center py-8">
            <Loader2 className="w-6 h-6 mr-2 animate-spin" />
            {isEnglish ? "Loading..." : "정보를 불러오는 중..."}
          </div>
        ) : (
          <div className="space-y-3">
            <div>
              <Label className="text-xs">{isEnglish ? "Supplier contact" : "공급업체 담당자"}</Label>
              <div className="border rounded-md p-2 bg-muted/30 max-h-[120px] overflow-y-auto text-sm">
                {managers.length === 0 ? (
                  <div className="text-muted-foreground text-center py-2">
                    {isEnglish ? "No contacts. Enter recipient directly." : "등록된 담당자가 없습니다. 수신인을 직접 입력해주세요."}
                  </div>
                ) : (
                  managers.map((m, i) => {
                    const email = m.email ?? "";
                    const id = `pom_manager_${i}_${email}`;
                    return (
                      <label key={id} htmlFor={id} className="flex items-center gap-2 py-1 cursor-pointer">
                        <input
                          type="checkbox"
                          id={id}
                          checked={!!checkedEmails[email]}
                          disabled={email === ""}
                          onChange={(e) => toggleManager(email, e.target.checked)}
                        />
                        <span>
                          {m.name}
                          {email && <span className="text-muted-foreground"> ({email})</span>}
                        </span>
                      </label>
                    );
                  })
                )}
              </div>
            </div>

            <div>
              <Label className="text-xs">
                {isEnglish ? "To" : "수신인"} <span className="text-red-500">*</span>
              </Label>
              <Input
                value={form.toEmails}
                onChange={(e) => setForm({ ...form, toEmails: e.target.value })}
                placeholder="email1@example.com, email2@example.com"
              />
              <p className="text-[11px] text-muted-foreground mt-1">
                {isEnglish ? "Multiple addresses separated by , or ;" : "여러 개는 쉼표(,) 또는 세미콜론(;)으로 구분"}
              </p>
            </div>

            <div>
              <Label className="text-xs">{isEnglish ? "CC" : "참조"}</Label>
              <Input
                value={form.ccEmails}
                onChange={(e) => setForm({ ...form, ccEmails: e.target.value })}
                placeholder={isEnglish ? "Optional" : "참조 이메일 주소 (선택사항)"}
              />
              <p className="text-[11px] text-muted-foreground mt-1">
                {isEnglish ? "Writer email is auto-added as CC." : "작성자 이메일이 자동으로 참조에 추가됩니다."}
              </p>
            </div>

            <div>
              <Label className="text-xs">
                {isEnglish ? "Subject" : "제목"} <span className="text-red-500">*</span>
              </Label>
              <Input
                value={form.subject}
                onChange={(e) => setForm({ ...form, subject: e.target.value })}
              />
            </div>

            <div>
              <Label className="text-xs">
                {isEnglish ? "Body" : "내용"} <span className="text-red-500">*</span>
              </Label>
              <Textarea
                rows={8}
                value={form.contents}
                onChange={(e) => setForm({ ...form, contents: e.target.value })}
              />
            </div>

            {sending && progress && (
              <div className="text-sm text-blue-600 dark:text-blue-400 flex items-center gap-2">
                <Loader2 className="w-4 h-4 animate-spin" />
                {progress}
              </div>
            )}
          </div>
        )}

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={sending}>
            {isEnglish ? "Cancel" : "취소"}
          </Button>
          <Button onClick={handleSend} disabled={loading || sending}>
            {sending ? <Loader2 className="w-4 h-4 mr-1 animate-spin" /> : <Send className="w-4 h-4 mr-1" />}
            {isEnglish ? "Send" : "발송"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
