"use client"

import { useState } from "react"
import { FieldGroup } from "@/components/admin/settings/field-group"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
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()

  return (
    <div className={embedded ? "space-y-4" : "space-y-6 rounded-lg border p-4"}>
      {!embedded ? (
        <div>
          <h3 className="text-sm font-medium">Montages WebDAV d&apos;organisation</h3>
          <p className="text-xs text-muted-foreground">
            Connecte un serveur WebDAV partagé (NAS, Nextcloud externe, etc.) visible par tous les
            utilisateurs UltiDrive.
          </p>
        </div>
      ) : null}

      <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>

      <div className="grid min-w-0 gap-4 sm:grid-cols-2">
        <FieldGroup>
          <Label htmlFor="webdav-org-slug">Slug organisation</Label>
          <Input
            id="webdav-org-slug"
            value={orgSlug}
            onChange={(e) => setOrgSlug(e.target.value)}
            placeholder="acme"
          />
        </FieldGroup>
        <FieldGroup>
          <Label htmlFor="webdav-display-name">Nom affiché</Label>
          <Input
            id="webdav-display-name"
            value={displayName}
            onChange={(e) => setDisplayName(e.target.value)}
            placeholder="NAS partagé"
          />
        </FieldGroup>
        <FieldGroup>
          <Label htmlFor="webdav-host">Hôte</Label>
          <Input
            id="webdav-host"
            value={host}
            onChange={(e) => setHost(e.target.value)}
            placeholder="nas.example.com"
          />
        </FieldGroup>
        <FieldGroup>
          <Label htmlFor="webdav-root">Chemin racine</Label>
          <Input
            id="webdav-root"
            value={root}
            onChange={(e) => setRoot(e.target.value)}
            placeholder="/remote.php/dav/files/user"
          />
        </FieldGroup>
        <FieldGroup>
          <Label htmlFor="webdav-user">Utilisateur</Label>
          <Input id="webdav-user" value={userName} onChange={(e) => setUserName(e.target.value)} />
        </FieldGroup>
        <FieldGroup>
          <Label htmlFor="webdav-pass">Mot de passe</Label>
          <Input
            id="webdav-pass"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete="new-password"
          />
        </FieldGroup>
      </div>

      <label className="flex cursor-pointer items-center gap-2 text-sm">
        <input type="checkbox" checked={secure} onChange={(e) => setSecure(e.target.checked)} />
        Connexion HTTPS
      </label>

      <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 rounded-md 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>
    </div>
  )
}
