"use client"

import Link from "next/link"
import { useLocale, useTranslations } from "next-intl"
import { useRouter } from "next/navigation"
import { useMemo, useState } from "react"
import { ArrowLeft, Loader2, Paperclip, Send, ShieldAlert } from "lucide-react"

import { createSupportTicket, type SupportCategory, type SupportPriority } from "@/src/lib/api/customer-portal-support"

function cx(...c: Array<string | false | null | undefined>) {
  return c.filter(Boolean).join(" ")
}

/** Same rules as Messages */
const MAX_FILE_MB = 10
const MAX_TOTAL_MB = 20
const MAX_FILE_BYTES = MAX_FILE_MB * 1024 * 1024
const MAX_TOTAL_BYTES = MAX_TOTAL_MB * 1024 * 1024

const ALLOWED_EXT = new Set([
  ".pdf",
  ".png", ".jpg", ".jpeg", ".webp", ".gif",
  ".doc", ".docx",
  ".xls", ".xlsx",
  ".ppt", ".pptx",
  ".txt", ".csv",
])

function getExt(name: string) {
  const n = (name || "").trim().toLowerCase()
  const i = n.lastIndexOf(".")
  return i >= 0 ? n.slice(i) : ""
}

function validateFilesFront(files: File[]) {
  let total = 0
  for (const f of files) {
    const ext = getExt(f.name)
    total += f.size

    if (!ALLOWED_EXT.has(ext)) return `File type not allowed: ${f.name}`
    if (f.size <= 0) return `Empty file is not allowed: ${f.name}`
    if (f.size > MAX_FILE_BYTES) return `File too large: ${f.name} (max ${MAX_FILE_MB} MB)`
    if (total > MAX_TOTAL_BYTES) return `Total upload too large (max ${MAX_TOTAL_MB} MB)`

    const lower = f.name.toLowerCase()
    if (lower.endsWith(".svg") || lower.endsWith(".zip") || lower.endsWith(".rar") || lower.endsWith(".7z")) {
      return `File type not allowed: ${f.name}`
    }
  }
  return null
}

const FILE_ACCEPT =
  ".pdf,.png,.jpg,.jpeg,.webp,.gif,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv"

export default function ClientSupportNewTicketPage() {
  const t = useTranslations("clientPortal")
  const locale = useLocale()
  const router = useRouter()

  const [subject, setSubject] = useState("")
  const [category, setCategory] = useState<SupportCategory>("other")
  const [priority, setPriority] = useState<SupportPriority>("normal")
  const [caseId, setCaseId] = useState<string>("")
  const [body, setBody] = useState("")
  const [files, setFiles] = useState<File[]>([])

  const [busy, setBusy] = useState(false)
  const [err, setErr] = useState<string | null>(null)

  const canSubmit = useMemo(() => subject.trim().length >= 4 && body.trim().length >= 8, [subject, body])

  async function submit() {
    if (!canSubmit || busy) return
    setErr(null)

    const msg = validateFilesFront(files)
    if (msg) {
      setErr(msg)
      return
    }

    setBusy(true)
    try {
      const created = await createSupportTicket({
        subject: subject.trim(),
        body: body.trim(),
        category,
        priority,
        case_id: caseId.trim() ? Number(caseId.trim()) : null,
        files,
      })

      // ✅ Redirect with success flag (professional)
      router.replace(`/${locale}/client/support/${created.id}?created=1`)
    } catch (e: any) {
      setErr(e?.message || t("common.error"))
    } finally {
      setBusy(false)
    }
  }

  const title = t("support.new.title")
  const subtitle = t("support.new.subtitle")

  return (
    <div className="space-y-4">
      <div className="flex items-start justify-between gap-3">
        <div>
          <h1 className="text-xl font-semibold">{title}</h1>
          <div className="text-sm text-muted-foreground">{subtitle}</div>
        </div>

        <Link
          href={`/${locale}/client/support`}
          className="inline-flex items-center gap-2 rounded-xl border bg-white px-3 py-2 text-sm hover:bg-black/5"
          style={{ borderColor: "rgba(15,23,42,.08)" }}
        >
          <ArrowLeft className="h-4 w-4" />
          {t("common.back")}
        </Link>
      </div>

      {err ? <div className="rounded-xl border border-red-200 bg-red-50 p-3 text-sm text-red-700">{err}</div> : null}

      <div className="rounded-2xl border bg-white p-5 space-y-4" style={{ borderColor: "rgba(15,23,42,.08)" }}>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          <div className="space-y-1">
            <label className="block text-xs text-slate-500">{t("support.new.fields.subject")} *</label>
            <input
              className="w-full rounded-xl border px-3 py-2 text-sm"
              style={{ borderColor: "rgba(15,23,42,.08)" }}
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              placeholder={t("support.new.fields.subjectPlaceholder")}
              disabled={busy}
            />
          </div>

          <div className="space-y-1">
            <label className="block text-xs text-slate-500">{t("support.new.fields.caseId")}</label>
            <input
              className="w-full rounded-xl border px-3 py-2 text-sm"
              style={{ borderColor: "rgba(15,23,42,.08)" }}
              value={caseId}
              onChange={(e) => setCaseId(e.target.value)}
              placeholder="ex: 12"
              disabled={busy}
            />
          </div>

          <div className="space-y-1">
            <label className="block text-xs text-slate-500">{t("support.new.fields.category")}</label>
            <select
              className="w-full rounded-xl border px-3 py-2 text-sm bg-white"
              style={{ borderColor: "rgba(15,23,42,.08)" }}
              value={category}
              onChange={(e) => setCategory(e.target.value as any)}
              disabled={busy}
            >
              <option value="access">{t("support.category.access")}</option>
              <option value="cases">{t("support.category.cases")}</option>
              <option value="documents">{t("support.category.documents")}</option>
              <option value="payments">{t("support.category.payments")}</option>
              <option value="other">{t("support.category.other")}</option>
            </select>
          </div>

          <div className="space-y-1">
            <label className="block text-xs text-slate-500">{t("support.new.fields.priority")}</label>
            <select
              className="w-full rounded-xl border px-3 py-2 text-sm bg-white"
              style={{ borderColor: "rgba(15,23,42,.08)" }}
              value={priority}
              onChange={(e) => setPriority(e.target.value as any)}
              disabled={busy}
            >
              <option value="normal">{t("support.priority.normal")}</option>
              <option value="urgent">{t("support.priority.urgent")}</option>
            </select>
          </div>
        </div>

        <div className="space-y-1">
          <label className="block text-xs text-slate-500">{t("support.new.fields.message")} *</label>
          <textarea
            className="w-full min-h-[160px] rounded-xl border px-3 py-2 text-sm"
            style={{ borderColor: "rgba(15,23,42,.08)" }}
            value={body}
            onChange={(e) => setBody(e.target.value)}
            placeholder={t("support.new.fields.messagePlaceholder")}
            disabled={busy}
          />
        </div>

        <div
          className="rounded-xl border p-3 flex items-start gap-3"
          style={{ borderColor: "rgba(245,158,11,0.30)", background: "rgba(245,158,11,0.10)" }}
        >
          <ShieldAlert className="h-5 w-5 text-amber-700" />
          <div className="min-w-0">
            <div className="text-sm font-semibold text-amber-900">{t("support.security.title")}</div>
            <div className="mt-1 text-sm text-amber-900/80">{t("support.security.body")}</div>
          </div>
        </div>

        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
          <label
            className="inline-flex items-center gap-2 rounded-xl border px-3 py-2 text-sm cursor-pointer hover:bg-black/5"
            style={{ borderColor: "rgba(15,23,42,.08)" }}
          >
            <Paperclip className="h-4 w-4 text-emerald-700" />
            {t("support.new.actions.attach")}
            <input
              type="file"
              className="hidden"
              multiple
              accept={FILE_ACCEPT}
              onChange={(e) => {
                const picked = Array.from(e.target.files || [])
                const msg = validateFilesFront(picked)
                if (msg) {
                  setErr(msg)
                  e.currentTarget.value = ""
                  return
                }
                setFiles(picked)
              }}
              disabled={busy}
            />
          </label>

          <div className="text-xs text-muted-foreground">
            {files.length > 0
              ? `${files.length} file(s) selected • max 10MB/file • 20MB total`
              : `max 10MB/file • 20MB total`}
          </div>

          <button
            type="button"
            onClick={submit}
            disabled={busy || !canSubmit}
            className={cx(
              "inline-flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-medium text-white",
              busy || !canSubmit ? "opacity-50" : "hover:bg-emerald-700"
            )}
            style={{ backgroundColor: "#10b981" }}
          >
            {busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
            {t("support.new.actions.submit")}
          </button>
        </div>
      </div>
    </div>
  )
}
