"use client";

import { type LDAPConfig, type LDAPTestResult, type LDAPFilterSuggestion } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Separator } from "@/components/ui/separator";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

interface LDAPTabProps {
  ldapConfig: LDAPConfig | null;
  ldapLoading: boolean;
  ldapSaving: boolean;
  ldapTesting: boolean;
  ldapError: string;
  ldapTestResult: LDAPTestResult | null;
  ldapForm: LDAPConfig;
  setLdapForm: React.Dispatch<React.SetStateAction<LDAPConfig>>;
  ldapChangePassword: boolean;
  setLdapChangePassword: (v: boolean) => void;
  onSave: (e: React.FormEvent) => void;
  onTest: () => void;
  onDelete: () => void;
}

export function LDAPTab({
  ldapConfig,
  ldapLoading,
  ldapSaving,
  ldapTesting,
  ldapError,
  ldapTestResult,
  ldapForm,
  setLdapForm,
  ldapChangePassword,
  setLdapChangePassword,
  onSave,
  onTest,
  onDelete,
}: LDAPTabProps) {
  return (
    <div className="mt-4 space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold">LDAP / Active Directory</h2>
        <div className="flex items-center gap-2">
          <span className="text-sm text-muted-foreground">LDAP aktiviert</span>
          <input
            type="checkbox"
            className="h-4 w-4"
            checked={ldapForm.enabled}
            onChange={(e) => setLdapForm((f) => ({ ...f, enabled: e.target.checked }))}
          />
        </div>
      </div>

      {ldapError && (
        <Alert variant="destructive">
          <AlertDescription>{ldapError}</AlertDescription>
        </Alert>
      )}

      {ldapLoading ? (
        <div className="space-y-3">
          {Array.from({ length: 6 }).map((_, i) => (
            <Skeleton key={i} className="h-10 w-full" />
          ))}
        </div>
      ) : (
        <form onSubmit={onSave} className="space-y-4">
          <Card>
            <CardContent className="pt-6 space-y-4">
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="ldap-url">Server-URL</Label>
                  <Input
                    id="ldap-url"
                    placeholder="ldap://server:389  oder  ldaps://server:636"
                    value={ldapForm.url}
                    onChange={(e) => setLdapForm((f) => ({ ...f, url: e.target.value }))}
                  />
                  <p className="text-xs text-muted-foreground">
                    Port frei wählbar · Standard: 389 (LDAP), 636 (LDAPS) · Univention UCS: 7389 / 7636
                  </p>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="ldap-bind-dn">Bind-DN (Service-Account)</Label>
                  <Input
                    id="ldap-bind-dn"
                    placeholder="CN=archivmail,OU=Service,DC=example,DC=com"
                    value={ldapForm.bind_dn}
                    onChange={(e) => setLdapForm((f) => ({ ...f, bind_dn: e.target.value }))}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="ldap-pw">Bind-Passwort</Label>
                  {ldapConfig && !ldapChangePassword ? (
                    <div className="flex gap-2">
                      <Input id="ldap-pw" type="password" value="••••••" readOnly className="flex-1" />
                      <Button type="button" variant="outline" size="sm" onClick={() => setLdapChangePassword(true)}>
                        Ändern
                      </Button>
                    </div>
                  ) : (
                    <Input
                      id="ldap-pw"
                      type="password"
                      placeholder="Neues Passwort eingeben"
                      value={ldapForm.bind_password}
                      onChange={(e) => setLdapForm((f) => ({ ...f, bind_password: e.target.value }))}
                    />
                  )}
                </div>
                <div className="space-y-2">
                  <Label htmlFor="ldap-base-dn">Base-DN</Label>
                  <Input
                    id="ldap-base-dn"
                    placeholder="DC=example,DC=com"
                    value={ldapForm.base_dn}
                    onChange={(e) => setLdapForm((f) => ({ ...f, base_dn: e.target.value }))}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="ldap-filter">User-Filter</Label>
                  <Input
                    id="ldap-filter"
                    placeholder="(sAMAccountName=%s)"
                    value={ldapForm.user_filter}
                    onChange={(e) => setLdapForm((f) => ({ ...f, user_filter: e.target.value }))}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="ldap-role">Standard-Rolle</Label>
                  <Select
                    value={ldapForm.default_role}
                    onValueChange={(v) => setLdapForm((f) => ({ ...f, default_role: v }))}
                  >
                    <SelectTrigger id="ldap-role">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="user">User</SelectItem>
                      <SelectItem value="auditor">Auditor</SelectItem>
                      <SelectItem value="admin">Admin</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <Separator />

              <div className="flex flex-wrap gap-6">
                <label className="flex items-center gap-2 text-sm cursor-pointer">
                  <input
                    type="checkbox"
                    className="h-4 w-4"
                    checked={ldapForm.tls}
                    onChange={(e) => setLdapForm((f) => ({ ...f, tls: e.target.checked }))}
                  />
                  STARTTLS verwenden
                </label>
                <label className="flex items-center gap-2 text-sm cursor-pointer">
                  <input
                    type="checkbox"
                    className="h-4 w-4"
                    checked={ldapForm.tls_skip_verify}
                    onChange={(e) => setLdapForm((f) => ({ ...f, tls_skip_verify: e.target.checked }))}
                  />
                  TLS-Zertifikat ignorieren
                  {ldapForm.tls_skip_verify && (
                    <Badge variant="destructive" className="text-xs ml-1">Unsicher</Badge>
                  )}
                </label>
              </div>

              <Separator />

              {/* Group mappings */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <Label>Gruppen-Rollenzuordnung</Label>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() =>
                      setLdapForm((f) => ({
                        ...f,
                        group_mappings: [...f.group_mappings, { group_dn: "", role: "user" }],
                      }))
                    }
                  >
                    + Hinzufügen
                  </Button>
                </div>
                {ldapForm.group_mappings.length === 0 ? (
                  <p className="text-sm text-muted-foreground">Keine Gruppen-Zuordnungen definiert.</p>
                ) : (
                  <div className="space-y-2">
                    {ldapForm.group_mappings.map((gm, i) => (
                      <div key={i} className="flex gap-2 items-center">
                        <Input
                          className="flex-1"
                          placeholder="CN=Archivadmins,OU=Groups,DC=example,DC=com"
                          value={gm.group_dn}
                          onChange={(e) => {
                            const gms = [...ldapForm.group_mappings];
                            gms[i] = { ...gms[i], group_dn: e.target.value };
                            setLdapForm((f) => ({ ...f, group_mappings: gms }));
                          }}
                        />
                        <Select
                          value={gm.role}
                          onValueChange={(v) => {
                            const gms = [...ldapForm.group_mappings];
                            gms[i] = { ...gms[i], role: v };
                            setLdapForm((f) => ({ ...f, group_mappings: gms }));
                          }}
                        >
                          <SelectTrigger className="w-32">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="user">User</SelectItem>
                            <SelectItem value="auditor">Auditor</SelectItem>
                            <SelectItem value="admin">Admin</SelectItem>
                          </SelectContent>
                        </Select>
                        <Button
                          type="button"
                          variant="destructive"
                          size="sm"
                          onClick={() => {
                            const gms = ldapForm.group_mappings.filter((_, j) => j !== i);
                            setLdapForm((f) => ({ ...f, group_mappings: gms }));
                          }}
                        >
                          Entfernen
                        </Button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </CardContent>
          </Card>

          {/* Test result */}
          {ldapTestResult && (
            <Card>
              <CardContent className="pt-4 space-y-3">
                <div className="flex items-center gap-2">
                  <Badge variant={ldapTestResult.ok ? "default" : "destructive"}>
                    {ldapTestResult.ok ? "Verbunden" : "Fehler"}
                  </Badge>
                  <span className="text-sm">{ldapTestResult.message}</span>
                  {ldapTestResult.latency_ms > 0 && (
                    <span className="text-xs text-muted-foreground">{ldapTestResult.latency_ms} ms</span>
                  )}
                </div>
                {ldapTestResult.server_info && (
                  <p className="text-xs text-muted-foreground font-mono">{ldapTestResult.server_info}</p>
                )}
                {ldapTestResult.error_detail && (
                  <p className="text-xs text-destructive font-mono">{ldapTestResult.error_detail}</p>
                )}
                {ldapTestResult.ok && ldapTestResult.users_found > 0 && (
                  <div className="space-y-1">
                    <p className="text-sm font-medium">
                      {ldapTestResult.users_found} Benutzer gefunden
                      {ldapTestResult.users?.length < ldapTestResult.users_found && (
                        <span className="text-muted-foreground font-normal"> (Vorschau: {ldapTestResult.users?.length})</span>
                      )}
                    </p>
                    <div className="rounded border overflow-auto max-h-64">
                      <table className="w-full text-xs">
                        <thead className="bg-muted sticky top-0">
                          <tr>
                            <th className="text-left px-2 py-1 font-medium">UID</th>
                            <th className="text-left px-2 py-1 font-medium">Name</th>
                            <th className="text-left px-2 py-1 font-medium">E-Mail</th>
                          </tr>
                        </thead>
                        <tbody>
                          {ldapTestResult.users?.map((u, i) => (
                            <tr key={i} className="border-t">
                              <td className="px-2 py-1 font-mono">{u.uid || "–"}</td>
                              <td className="px-2 py-1">{u.display_name || "–"}</td>
                              <td className="px-2 py-1 text-muted-foreground">{u.mail || "–"}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>
                )}
                {ldapTestResult.ok && ldapTestResult.filter_suggestions?.length > 0 && (
                  <div className="space-y-2 pt-1">
                    <p className="text-xs font-medium text-muted-foreground">Filter-Vorschläge — klicken zum Übernehmen:</p>
                    <div className="flex flex-wrap gap-2">
                      {ldapTestResult.filter_suggestions.map((s: LDAPFilterSuggestion, i: number) => (
                        <button
                          key={i}
                          type="button"
                          title={s.description}
                          onClick={() => setLdapForm((f) => ({ ...f, user_filter: s.filter }))}
                          className="inline-flex items-center px-2 py-1 rounded text-xs border border-border bg-muted hover:bg-accent hover:text-accent-foreground transition-colors cursor-pointer font-mono"
                        >
                          {s.label}
                        </button>
                      ))}
                    </div>
                    <p className="text-xs text-muted-foreground">
                      <span className="font-mono">%s</span> wird beim Login durch den Benutzernamen ersetzt
                    </p>
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* Action bar */}
          <div className="flex flex-wrap gap-2">
            <Button type="button" variant="outline" onClick={onTest} disabled={ldapTesting || ldapSaving}>
              {ldapTesting ? "Teste..." : "Verbindung testen"}
            </Button>
            <Button type="submit" disabled={ldapSaving || ldapTesting}>
              {ldapSaving ? "Speichern..." : "Speichern"}
            </Button>
            {ldapConfig && (
              <Button
                type="button"
                variant="destructive"
                disabled={ldapSaving}
                onClick={onDelete}
              >
                Konfiguration löschen
              </Button>
            )}
          </div>
        </form>
      )}

      {ldapConfig && (
        <p className="text-xs text-muted-foreground">
          Zuletzt geändert: {ldapConfig.updated_at ? new Date(ldapConfig.updated_at).toLocaleString("de-DE") : "–"}
          {ldapConfig.updated_by ? ` von ${ldapConfig.updated_by}` : ""}
        </p>
      )}
    </div>
  );
}
