"use client"

import { useState } from "react"
import {
  SettingsCard,
  SettingsCheckboxRow,
  SettingsField,
  SettingsGrid,
} from "@/components/settings/settings-kit"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import {
  useAdminDriveOrgMountMutations,
  useAdminDriveOrgMounts,
} from "@/lib/api/hooks/use-admin-drive-queries"

function mountStatusLabel(status: string) {
  switch (status) {
    case "active":
      return "Actif"
    case "error":
      return "Erreur"
    case "pending":
      return "En attente"
    default:
      return status
  }
}

export function DriveOrgWebDAVSection({ embedded = false }: { embedded?: boolean }) {
  const mounts = useAdminDriveOrgMounts()
  const { create, remove } = useAdminDriveOrgMountMutations()

  const [orgSlug, setOrgSlug] = useState("")
  const [displayName, setDisplayName] = useState("")
  const [host, setHost] = useState("")
  const [root, setRoot] = useState("/")
  const [userName, setUserName] = useState("")
  const [password, setPassword] = useState("")
  const [secure, setSecure] = useState(true)

  const canCreate =
    orgSlug.trim() &&
    displayName.trim() &&
    host.trim() &&
    userName.trim() &&
    password.trim()

  const content = (
    <>
      <p className="text-xs text-muted-foreground">
        Le slug d&apos;organisation sert au rattachement administratif. Le volume est monté globalement
        dans Nextcloud et apparaît dans UltiDrive pour tous les utilisateurs.
      </p>

      <SettingsGrid columns={2}>
        <SettingsField label="Slug organisation" htmlFor="webdav-org-slug">
          <Input
            id="webdav-org-slug"
            className="h-9"
            value={orgSlug}
            onChange={(e) => setOrgSlug(e.target.value)}
            placeholder="acme"
          />
        </SettingsField>
        <SettingsField label="Nom affiché" htmlFor="webdav-display-name">
          <Input
            id="webdav-display-name"
            className="h-9"
            value={displayName}
            onChange={(e) => setDisplayName(e.target.value)}
            placeholder="NAS partagé"
          />
        </SettingsField>
        <SettingsField label="Hôte" htmlFor="webdav-host">
          <Input
            id="webdav-host"
            className="h-9"
            value={host}
            onChange={(e) => setHost(e.target.value)}
            placeholder="nas.example.com"
          />
        </SettingsField>
        <SettingsField label="Chemin racine" htmlFor="webdav-root">
          <Input
            id="webdav-root"
            className="h-9"
            value={root}
            onChange={(e) => setRoot(e.target.value)}
            placeholder="/remote.php/dav/files/user"
          />
        </SettingsField>
        <SettingsField label="Utilisateur" htmlFor="webdav-user">
          <Input
            id="webdav-user"
            className="h-9"
            value={userName}
            onChange={(e) => setUserName(e.target.value)}
          />
        </SettingsField>
        <SettingsField label="Mot de passe" htmlFor="webdav-pass">
          <Input
            id="webdav-pass"
            className="h-9"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete="new-password"
          />
        </SettingsField>
      </SettingsGrid>

      <SettingsCheckboxRow
        title="Connexion HTTPS"
        checked={secure}
        onCheckedChange={setSecure}
      />

      <Button
        size="sm"
        disabled={!canCreate || create.isPending}
        onClick={() =>
          void create.mutateAsync({
            org_slug: orgSlug.trim(),
            display_name: displayName.trim(),
            webdav: {
              host: host.trim(),
              root: root.trim() || "/",
              user: userName.trim(),
              password,
              secure,
            },
          }).then(() => {
            setOrgSlug("")
            setDisplayName("")
            setHost("")
            setRoot("/")
            setUserName("")
            setPassword("")
            setSecure(true)
          })
        }
      >
        Ajouter le montage
      </Button>

      <ul className="divide-y divide-mail-border rounded-md border border-mail-border text-sm">
        {(mounts.data ?? []).map((mount) => (
          <li key={mount.id} className="flex items-start justify-between gap-3 px-3 py-2">
            <div className="min-w-0 space-y-1">
              <div className="flex flex-wrap items-center gap-2">
                <p className="truncate font-medium">{mount.display_name}</p>
                <Badge variant={mount.status === "active" ? "secondary" : "destructive"} className="text-[10px]">
                  {mountStatusLabel(mount.status)}
                </Badge>
              </div>
              <p className="truncate text-xs text-muted-foreground">
                {mount.org_slug ?? "—"} · WebDAV · {mount.mount_point}
              </p>
              {mount.last_error ? (
                <p className="text-xs text-destructive">{mount.last_error}</p>
              ) : null}
            </div>
            <Button
              size="sm"
              variant="ghost"
              className="shrink-0 text-destructive"
              disabled={remove.isPending}
              onClick={() => void remove.mutateAsync(mount.id)}
            >
              Supprimer
            </Button>
          </li>
        ))}
        {mounts.data?.length === 0 ? (
          <li className="px-3 py-4 text-center text-muted-foreground">Aucun montage WebDAV d&apos;organisation</li>
        ) : null}
      </ul>
    </>
  )

  if (embedded) return <div className="space-y-4">{content}</div>

  return (
    <SettingsCard
      title="Montages WebDAV d'organisation"
      description="Connecte un serveur WebDAV partagé (NAS, Nextcloud externe, etc.) visible par tous les utilisateurs UltiDrive."
    >
      {content}
    </SettingsCard>
  )
}
