"use client";

import { useState, useEffect } from "react";
import { X, Copy, Check, Shield, AlertTriangle, ChevronDown, ChevronRight, Users, Trash2, Loader2 } from "lucide-react";
import { useAuth } from "@/lib/auth";
import { useTeams } from "@/lib/use-data";
import { addTeamRepo, removeTeamRepo, listTeamRepos } from "@/lib/api";
import { useToast } from "@/components/toast";

interface ShareVaultModalProps {
  open: boolean;
  vaultName: string;
  onClose: () => void;
}

export function ShareVaultModal({ open, vaultName, onClose }: ShareVaultModalProps) {
  const { auth } = useAuth();
  const { teams, loading: teamsLoading } = useTeams();
  const { showToast } = useToast();
  const [copiedField, setCopiedField] = useState<string | null>(null);
  const [showTokenFallback, setShowTokenFallback] = useState(false);

  // Team sharing state
  const [selectedTeam, setSelectedTeam] = useState("");
  const [permission, setPermission] = useState("push");
  const [sharing, setSharing] = useState(false);
  const [teamAccess, setTeamAccess] = useState<{ org: string; slug: string; name: string }[]>([]);
  const [loadingAccess, setLoadingAccess] = useState(true);

  // Load which teams already have access to this vault
  useEffect(() => {
    if (!open || !teams.length) {
      setLoadingAccess(false);
      return;
    }
    setLoadingAccess(true);
    const checkAccess = async () => {
      const accessList: { org: string; slug: string; name: string }[] = [];
      for (const team of teams) {
        try {
          const repos = await listTeamRepos(team.org, team.slug);
          if (Array.isArray(repos) && repos.some((r: any) => r.full_name === vaultName)) {
            accessList.push({ org: team.org, slug: team.slug, name: team.name });
          }
        } catch {
          // skip
        }
      }
      setTeamAccess(accessList);
      setLoadingAccess(false);
    };
    checkAccess();
  }, [open, teams, vaultName]);

  if (!open || !auth) return null;

  const serverUrl = auth.serverUrl;
  const token = auth.token;

  const connectionConfig = JSON.stringify({
    baseUrl: serverUrl,
    authScheme: "token",
    token: token,
  }, null, 2);

  function copyToClipboard(text: string, field: string) {
    navigator.clipboard.writeText(text);
    setCopiedField(field);
    setTimeout(() => setCopiedField(null), 2000);
  }

  const handleShareWithTeam = async () => {
    if (!selectedTeam) return;
    setSharing(true);
    try {
      const [teamOrg, teamSlug] = selectedTeam.split("/");
      const [vaultOwner, vaultRepo] = vaultName.split("/");
      const result = await addTeamRepo(teamOrg, teamSlug, vaultOwner, vaultRepo, permission);
      if (result) {
        const team = teams.find((t) => `${t.org}/${t.slug}` === selectedTeam);
        setTeamAccess((prev) => [...prev, { org: teamOrg, slug: teamSlug, name: team?.name || teamSlug }]);
        setSelectedTeam("");
        showToast("Vault shared with team");
      } else {
        showToast("Failed to share vault", "error");
      }
    } catch {
      showToast("Failed to share vault", "error");
    } finally {
      setSharing(false);
    }
  };

  const handleRevokeAccess = async (teamOrg: string, teamSlug: string) => {
    const [vaultOwner, vaultRepo] = vaultName.split("/");
    const result = await removeTeamRepo(teamOrg, teamSlug, vaultOwner, vaultRepo);
    if (result !== null) {
      setTeamAccess((prev) => prev.filter((t) => !(t.org === teamOrg && t.slug === teamSlug)));
      showToast("Team access revoked");
    } else {
      showToast("Failed to revoke access", "error");
    }
  };

  // Teams that don't already have access
  const availableTeams = teams.filter(
    (t) => !teamAccess.some((a) => a.org === t.org && a.slug === t.slug)
  );

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative bg-surface border border-border rounded-xl w-full max-w-lg p-6 max-h-[85vh] overflow-y-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-5">
          <h2 className="text-lg font-semibold text-text-primary">Share Vault</h2>
          <button onClick={onClose} className="p-1.5 rounded-md hover:bg-surface-elevated text-text-secondary hover:text-text-primary">
            <X size={16} />
          </button>
        </div>

        {/* Team Sharing */}
        <div className="mb-5">
          <h3 className="text-sm font-medium text-text-primary mb-3 flex items-center gap-2">
            <Users size={16} className="text-accent" />
            Share with Team
          </h3>

          {teamsLoading ? (
            <div className="flex items-center gap-2 py-4 text-sm text-text-muted">
              <Loader2 size={14} className="animate-spin" />
              Loading teams...
            </div>
          ) : teams.length === 0 ? (
            <p className="text-sm text-text-muted py-3">
              No teams found. Create a team first from the sidebar.
            </p>
          ) : (
            <div className="space-y-3">
              {/* Select team + permission */}
              {availableTeams.length > 0 && (
                <div className="flex gap-2">
                  <select
                    value={selectedTeam}
                    onChange={(e) => setSelectedTeam(e.target.value)}
                    className="flex-1 px-3 py-2 bg-background border border-border-light rounded-md text-sm text-text-primary focus:outline-none focus:border-accent"
                  >
                    <option value="">Select a team...</option>
                    {availableTeams.map((t) => (
                      <option key={`${t.org}/${t.slug}`} value={`${t.org}/${t.slug}`}>
                        {t.org}/{t.name}
                      </option>
                    ))}
                  </select>
                  <select
                    value={permission}
                    onChange={(e) => setPermission(e.target.value)}
                    className="px-3 py-2 bg-background border border-border-light rounded-md text-sm text-text-primary focus:outline-none focus:border-accent"
                  >
                    <option value="pull">Read</option>
                    <option value="push">Write</option>
                    <option value="admin">Admin</option>
                  </select>
                  <button
                    onClick={handleShareWithTeam}
                    disabled={sharing || !selectedTeam}
                    className="px-4 py-2 text-sm font-medium rounded-md bg-accent text-white hover:bg-accent-hover disabled:opacity-50 transition-colors"
                  >
                    {sharing ? <Loader2 size={14} className="animate-spin" /> : "Share"}
                  </button>
                </div>
              )}

              {/* Teams with access */}
              {loadingAccess ? (
                <div className="flex items-center gap-2 py-2 text-sm text-text-muted">
                  <Loader2 size={14} className="animate-spin" />
                  Checking team access...
                </div>
              ) : teamAccess.length > 0 ? (
                <div>
                  <p className="text-[11px] font-medium text-text-muted uppercase tracking-wider mb-2">
                    Teams with access
                  </p>
                  <div className="space-y-1">
                    {teamAccess.map((t) => (
                      <div
                        key={`${t.org}/${t.slug}`}
                        className="flex items-center justify-between px-3 py-2 rounded-md bg-background border border-border-light"
                      >
                        <div className="flex items-center gap-2">
                          <Users size={14} className="text-text-muted" />
                          <span className="text-sm text-text-primary">{t.org}/{t.name}</span>
                        </div>
                        <button
                          onClick={() => handleRevokeAccess(t.org, t.slug)}
                          className="p-1 rounded text-text-muted hover:text-error hover:bg-error/10 transition-colors"
                          title="Revoke access"
                        >
                          <Trash2 size={12} />
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              ) : (
                <p className="text-xs text-text-muted">No teams have access to this vault yet.</p>
              )}
            </div>
          )}
        </div>

        {/* Divider */}
        <div className="border-t border-border-light my-5" />

        {/* Token Fallback (collapsed) */}
        <div>
          <button
            onClick={() => setShowTokenFallback(!showTokenFallback)}
            className="flex items-center gap-2 w-full text-left text-sm text-text-muted hover:text-text-secondary transition-colors"
          >
            {showTokenFallback ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
            <span>Share via access token (advanced)</span>
          </button>

          {showTokenFallback && (
            <div className="mt-3 space-y-3">
              {/* Warning */}
              <div className="flex gap-3 p-3 rounded-lg bg-warning/10 border border-warning/20">
                <AlertTriangle size={16} className="text-warning shrink-0 mt-0.5" />
                <div className="text-xs text-text-secondary leading-relaxed">
                  <strong className="text-text-primary">Full access token.</strong> Anyone with this token has complete read/write access to all your vaults. Only share with people you trust.
                </div>
              </div>

              {/* Server URL */}
              <div>
                <label className="text-[11px] font-medium text-text-muted uppercase tracking-wider mb-1 block">Server URL</label>
                <div className="flex items-center gap-2">
                  <code className="flex-1 px-3 py-2 bg-background border border-border-light rounded-md text-sm text-text-primary font-mono truncate">
                    {serverUrl}
                  </code>
                  <button
                    onClick={() => copyToClipboard(serverUrl, "url")}
                    className="p-2 rounded-md border border-border hover:bg-surface-elevated text-text-secondary hover:text-text-primary transition-colors"
                  >
                    {copiedField === "url" ? <Check size={14} className="text-success" /> : <Copy size={14} />}
                  </button>
                </div>
              </div>

              {/* Token */}
              <div>
                <label className="text-[11px] font-medium text-text-muted uppercase tracking-wider mb-1 block">Access Token</label>
                <div className="flex items-center gap-2">
                  <code className="flex-1 px-3 py-2 bg-background border border-border-light rounded-md text-sm text-text-primary font-mono truncate">
                    {token.slice(0, 8)}{"*".repeat(24)}{token.slice(-4)}
                  </code>
                  <button
                    onClick={() => copyToClipboard(token, "token")}
                    className="p-2 rounded-md border border-border hover:bg-surface-elevated text-text-secondary hover:text-text-primary transition-colors"
                  >
                    {copiedField === "token" ? <Check size={14} className="text-success" /> : <Copy size={14} />}
                  </button>
                </div>
              </div>

              {/* Connection Config JSON */}
              <div>
                <div className="flex items-center justify-between mb-1">
                  <label className="text-[11px] font-medium text-text-muted uppercase tracking-wider">Connection Config</label>
                  <button
                    onClick={() => copyToClipboard(connectionConfig, "config")}
                    className="flex items-center gap-1 text-xs text-accent hover:text-accent-hover transition-colors"
                  >
                    {copiedField === "config" ? <><Check size={12} className="text-success" /> Copied</> : <><Copy size={12} /> Copy</>}
                  </button>
                </div>
                <pre className="px-3 py-2 bg-background border border-border-light rounded-md text-xs text-text-secondary font-mono overflow-x-auto">
                  {connectionConfig}
                </pre>
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center gap-2 mt-5 pt-4 border-t border-border-light">
          <Shield size={14} className="text-text-muted" />
          <p className="text-xs text-text-muted flex-1">
            Team members will see this vault in their shared vaults.
          </p>
          <button
            onClick={onClose}
            className="px-4 py-1.5 text-sm font-medium rounded-md bg-surface-elevated border border-border text-text-primary hover:bg-background transition-colors"
          >
            Done
          </button>
        </div>
      </div>
    </div>
  );
}
