import { defineRouteConfig } from "@medusajs/admin-sdk"
import { useEffect, useState, type FormEvent } from "react"

type AdminCompanyReview = {
  id: string
  author_name: string
  rating: number
  body: string
  is_published: boolean
  created_at?: string | null
}

function formatDate(value?: string | null) {
  if (!value) {
    return "-"
  }

  const date = new Date(value)
  if (Number.isNaN(date.getTime())) {
    return "-"
  }

  return new Intl.DateTimeFormat("fr-FR", { dateStyle: "medium", timeStyle: "short" }).format(date)
}

type EditDraft = {
  author_name: string
  rating: number
  body: string
}

const AvisEntreprisePage = () => {
  const [reviews, setReviews] = useState<AdminCompanyReview[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState("")
  const [submitting, setSubmitting] = useState(false)
  const [editingId, setEditingId] = useState<string>("")
  const [editDraft, setEditDraft] = useState<EditDraft>({ author_name: "", rating: 5, body: "" })
  const [savingEdit, setSavingEdit] = useState(false)

  const loadReviews = async () => {
    setLoading(true)
    setError("")

    try {
      const response = await fetch("/admin/custom/company-reviews", { credentials: "include" })
      if (!response.ok) {
        throw new Error("Impossible de charger les avis.")
      }
      const payload = (await response.json()) as { reviews?: AdminCompanyReview[] }
      setReviews(payload.reviews || [])
    } catch (e) {
      setError(e instanceof Error ? e.message : "Impossible de charger les avis.")
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    void loadReviews()
  }, [])

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    const form = event.currentTarget
    const formData = new FormData(form)
    setSubmitting(true)
    setError("")

    try {
      const response = await fetch("/admin/custom/company-reviews", {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          author_name: formData.get("author_name"),
          rating: Number(formData.get("rating")),
          body: formData.get("body"),
        }),
      })

      if (!response.ok) {
        throw new Error("Impossible de creer l'avis.")
      }

      form.reset()
      await loadReviews()
    } catch (e) {
      setError(e instanceof Error ? e.message : "Impossible de creer l'avis.")
    } finally {
      setSubmitting(false)
    }
  }

  const togglePublished = async (review: AdminCompanyReview) => {
    try {
      await fetch(`/admin/custom/company-reviews/${review.id}`, {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ is_published: !review.is_published }),
      })
      await loadReviews()
    } catch {
      setError("Impossible de mettre a jour l'avis.")
    }
  }

  const startEdit = (review: AdminCompanyReview) => {
    setError("")
    setEditingId(review.id)
    setEditDraft({ author_name: review.author_name, rating: review.rating, body: review.body })
  }

  const cancelEdit = () => {
    setEditingId("")
  }

  const saveEdit = async (id: string) => {
    const authorName = editDraft.author_name.trim()
    const body = editDraft.body.trim()

    if (!authorName || !body) {
      setError("Le nom et l'avis ne peuvent pas etre vides.")
      return
    }

    setSavingEdit(true)
    setError("")

    try {
      const response = await fetch(`/admin/custom/company-reviews/${id}`, {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          author_name: authorName,
          rating: editDraft.rating,
          body,
        }),
      })

      if (!response.ok) {
        throw new Error("Impossible de modifier l'avis.")
      }

      setEditingId("")
      await loadReviews()
    } catch (e) {
      setError(e instanceof Error ? e.message : "Impossible de modifier l'avis.")
    } finally {
      setSavingEdit(false)
    }
  }

  const deleteReview = async (review: AdminCompanyReview) => {
    if (!window.confirm(`Supprimer l'avis de ${review.author_name} ?`)) {
      return
    }

    try {
      await fetch(`/admin/custom/company-reviews/${review.id}`, {
        method: "DELETE",
        credentials: "include",
      })
      await loadReviews()
    } catch {
      setError("Impossible de supprimer l'avis.")
    }
  }

  return (
    <div className="flex flex-col gap-y-6">
      <div>
        <h1 className="text-2xl font-semibold">Avis sur l&apos;entreprise</h1>
        <p className="text-ui-fg-subtle mt-2 text-sm">
          Avis affiches sur la page d&apos;accueil du site (ex: repris de Google, Trustpilot, ou saisis a la main).
        </p>
      </div>

      <section className="border-ui-border-base rounded-lg border px-6 py-5">
        <p className="text-sm font-semibold">Ajouter un avis</p>
        <form onSubmit={handleSubmit} className="mt-4 grid gap-4 md:grid-cols-2">
          <label className="grid gap-1.5 text-sm">
            <span className="font-medium">Nom</span>
            <input
              name="author_name"
              type="text"
              required
              maxLength={80}
              className="bg-ui-bg-field border-ui-border-base h-10 rounded-md border px-3 outline-none"
            />
          </label>
          <label className="grid gap-1.5 text-sm">
            <span className="font-medium">Note</span>
            <select
              name="rating"
              defaultValue={5}
              className="bg-ui-bg-field border-ui-border-base h-10 rounded-md border px-3 outline-none"
            >
              {[5, 4, 3, 2, 1].map((value) => (
                <option key={value} value={value}>
                  {value} / 5
                </option>
              ))}
            </select>
          </label>
          <label className="grid gap-1.5 text-sm md:col-span-2">
            <span className="font-medium">Avis</span>
            <textarea
              name="body"
              required
              rows={3}
              maxLength={2000}
              className="bg-ui-bg-field border-ui-border-base rounded-md border px-3 py-2 outline-none"
            />
          </label>
          <div className="md:col-span-2">
            <button
              type="submit"
              disabled={submitting}
              className="bg-ui-button-inverted text-ui-fg-on-inverted inline-flex h-9 items-center rounded-md px-4 text-sm font-medium disabled:opacity-60"
            >
              {submitting ? "Ajout..." : "Ajouter l'avis"}
            </button>
          </div>
        </form>
      </section>

      {error ? <p className="text-ui-fg-error text-sm">{error}</p> : null}

      <section className="border-ui-border-base overflow-hidden rounded-lg border">
        <div className="px-6 py-4">
          <p className="text-sm font-semibold">{reviews.length} avis</p>
        </div>

        {loading ? (
          <div className="px-6 py-10">
            <p className="text-ui-fg-subtle text-sm">Chargement...</p>
          </div>
        ) : reviews.length === 0 ? (
          <div className="px-6 py-10">
            <p className="text-ui-fg-subtle text-sm">Aucun avis pour le moment.</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full border-collapse text-sm">
              <thead>
                <tr className="border-ui-border-base border-y bg-ui-bg-subtle">
                  <th className="px-6 py-3 text-left font-medium">Nom</th>
                  <th className="px-6 py-3 text-left font-medium">Note</th>
                  <th className="px-6 py-3 text-left font-medium">Avis</th>
                  <th className="px-6 py-3 text-left font-medium">Date</th>
                  <th className="px-6 py-3 text-left font-medium">Statut</th>
                  <th className="px-6 py-3 text-left font-medium">Actions</th>
                </tr>
              </thead>
              <tbody>
                {reviews.map((review) => {
                  const isEditing = editingId === review.id

                  return (
                    <tr key={review.id} className="border-ui-border-base border-b align-top">
                      <td className="px-6 py-3 font-medium">
                        {isEditing ? (
                          <input
                            value={editDraft.author_name}
                            onChange={(event) => setEditDraft((draft) => ({ ...draft, author_name: event.target.value }))}
                            maxLength={80}
                            className="bg-ui-bg-field border-ui-border-base h-9 w-full rounded-md border px-2 outline-none"
                          />
                        ) : (
                          review.author_name
                        )}
                      </td>
                      <td className="px-6 py-3">
                        {isEditing ? (
                          <select
                            value={editDraft.rating}
                            onChange={(event) => setEditDraft((draft) => ({ ...draft, rating: Number(event.target.value) }))}
                            className="bg-ui-bg-field border-ui-border-base h-9 rounded-md border px-2 outline-none"
                          >
                            {[5, 4, 3, 2, 1].map((value) => (
                              <option key={value} value={value}>
                                {value} / 5
                              </option>
                            ))}
                          </select>
                        ) : (
                          "★".repeat(review.rating)
                        )}
                      </td>
                      <td className="px-6 py-3 max-w-sm">
                        {isEditing ? (
                          <textarea
                            value={editDraft.body}
                            onChange={(event) => setEditDraft((draft) => ({ ...draft, body: event.target.value }))}
                            rows={3}
                            maxLength={2000}
                            className="bg-ui-bg-field border-ui-border-base w-full rounded-md border px-2 py-1 outline-none"
                          />
                        ) : (
                          <p className="line-clamp-3">{review.body}</p>
                        )}
                      </td>
                      <td className="px-6 py-3">{formatDate(review.created_at)}</td>
                      <td className="px-6 py-3">
                        <span
                          className={`inline-flex rounded-full border px-2 py-1 text-xs font-medium ${
                            review.is_published
                              ? "bg-green-100 text-green-700 border-green-200"
                              : "bg-ui-bg-subtle text-ui-fg-subtle border-ui-border-base"
                          }`}
                        >
                          {review.is_published ? "Publie" : "Masque"}
                        </span>
                      </td>
                      <td className="px-6 py-3">
                        {isEditing ? (
                          <div className="flex gap-2">
                            <button
                              type="button"
                              onClick={() => void saveEdit(review.id)}
                              disabled={savingEdit}
                              className="bg-ui-button-inverted text-ui-fg-on-inverted txt-compact-small-plus inline-flex h-8 items-center rounded-md px-3 disabled:opacity-60"
                            >
                              {savingEdit ? "Enregistrement..." : "Enregistrer"}
                            </button>
                            <button
                              type="button"
                              onClick={cancelEdit}
                              disabled={savingEdit}
                              className="bg-ui-bg-base border-ui-border-base txt-compact-small-plus inline-flex h-8 items-center rounded-md border px-3"
                            >
                              Annuler
                            </button>
                          </div>
                        ) : (
                          <div className="flex flex-wrap gap-2">
                            <button
                              type="button"
                              onClick={() => startEdit(review)}
                              className="bg-ui-bg-base border-ui-border-base txt-compact-small-plus inline-flex h-8 items-center rounded-md border px-3"
                            >
                              Modifier
                            </button>
                            <button
                              type="button"
                              onClick={() => void togglePublished(review)}
                              className="bg-ui-bg-base border-ui-border-base txt-compact-small-plus inline-flex h-8 items-center rounded-md border px-3"
                            >
                              {review.is_published ? "Masquer" : "Publier"}
                            </button>
                            <button
                              type="button"
                              onClick={() => void deleteReview(review)}
                              className="text-ui-fg-error border-ui-border-base txt-compact-small-plus inline-flex h-8 items-center rounded-md border px-3"
                            >
                              Supprimer
                            </button>
                          </div>
                        )}
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </div>
  )
}

export const config = defineRouteConfig({
  label: "Avis entreprise",
})

export default AvisEntreprisePage
