"use client";

import { PhoneInput } from "@/components/PhoneInput";
import { Alert } from "@/components/ui/Alert";
import { FormField } from "@/components/ui/FormField";
import { apiFetch } from "@/lib/api";
import { useLocale, useTranslations } from "next-intl";
import { FormEvent, useEffect, useState } from "react";

export function SupportMessageForm({
  onSent,
  onCancel,
}: {
  onSent: () => void;
  onCancel: () => void;
}) {
  const t = useTranslations("support");
  const tc = useTranslations("common");
  const locale = useLocale();
  const [form, setForm] = useState({ name: "", phone: "", message: "" });
  const [sending, setSending] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    void (async () => {
      const res = await apiFetch<{
        username?: string;
        name?: string;
        phone?: string;
      }>("/driver-company/profile", { locale });
      if (res.data) {
        setForm((f) => ({
          ...f,
          name: res.data?.username ?? res.data?.name ?? f.name,
          phone: res.data?.phone ?? f.phone,
        }));
      }
    })();
  }, [locale]);

  const send = async (e: FormEvent) => {
    e.preventDefault();
    setError("");
    if (!form.name.trim() || !form.phone.trim() || !form.message.trim()) {
      setError(t("required"));
      return;
    }
    setSending(true);
    const res = await apiFetch("/driver-company/support", {
      method: "POST",
      body: form,
      locale,
    });
    setSending(false);
    if (!res.ok) {
      setError(res.message ?? tc("error"));
      return;
    }
    onSent();
  };

  return (
    <form onSubmit={send} className="space-y-2">
      {error ? <Alert type="error" message={error} /> : null}
      <p className="text-sm text-muted-foreground">{t("hint")}</p>
      <FormField label={t("username")}>
        <input
          required
          value={form.name}
          onChange={(e) => setForm({ ...form, name: e.target.value })}
        />
      </FormField>
      <FormField label={t("phone")}>
        <PhoneInput
          value={form.phone}
          onChange={(phone) => setForm({ ...form, phone })}
        />
      </FormField>
      <FormField label={t("messageLabel")}>
        <textarea
          required
          rows={5}
          value={form.message}
          onChange={(e) => setForm({ ...form, message: e.target.value })}
        />
      </FormField>
      <div className="flex justify-end gap-2 pt-2">
        <button type="button" className="btn-secondary" onClick={onCancel}>
          {tc("cancel")}
        </button>
        <button type="submit" className="btn-primary" disabled={sending}>
          {sending ? tc("loading") : tc("submit")}
        </button>
      </div>
    </form>
  );
}
