"use client";

import { useState, useEffect, useMemo } from "react";
import { Linkedin, Twitter, Facebook, Instagram } from "lucide-react";
import type { Network } from "@/lib/types";

export interface SocialAccountInfo {
  id: string;
  network: Network;
  accountName: string;
  accountId: string;
  avatarUrl?: string;
}

type SocialAccountItem = SocialAccountInfo;

const NETWORK_ICON: Record<Network, typeof Linkedin> = {
  LINKEDIN: Linkedin,
  TWITTER: Twitter,
  FACEBOOK: Facebook,
  INSTAGRAM: Instagram,
};

const NETWORK_COLOR: Record<Network, string> = {
  LINKEDIN: "#0A66C2",
  TWITTER: "#1DA1F2",
  FACEBOOK: "#1877F2",
  INSTAGRAM: "#E4405F",
};

const NETWORK_LABEL: Record<Network, string> = {
  LINKEDIN: "LinkedIn",
  TWITTER: "Twitter",
  FACEBOOK: "Facebook",
  INSTAGRAM: "Instagram",
};

const NETWORK_ORDER: Network[] = ["TWITTER", "LINKEDIN", "FACEBOOK", "INSTAGRAM"];

interface AccountSelectorProps {
  selectedIds: string[];
  onChange: (ids: string[], networks: Network[], accounts: SocialAccountInfo[]) => void;
}

export function AccountSelector({ selectedIds, onChange }: AccountSelectorProps) {
  const [accounts, setAccounts] = useState<SocialAccountItem[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/v1/social-accounts")
      .then((res) => (res.ok ? res.json() : []))
      .then((data: SocialAccountItem[]) => setAccounts(data))
      .catch(() => setAccounts([]))
      .finally(() => setLoading(false));
  }, []);

  // Group accounts by network, preserving NETWORK_ORDER — show ALL platforms
  const grouped = useMemo(() => {
    const map = new Map<Network, SocialAccountItem>();
    for (const account of accounts) {
      if (!map.has(account.network)) {
        map.set(account.network, account);
      }
    }
    // Return ALL platforms in canonical order (connected or not)
    return NETWORK_ORDER.map((n) => ({
      network: n,
      accounts: map.has(n) ? [map.get(n)!] : [],
      connected: map.has(n),
    }));
  }, [accounts]);

  const emitChange = (nextIds: string[]) => {
    const selected = accounts.filter((a) => nextIds.includes(a.id));
    const networks = [...new Set(selected.map((a) => a.network))];
    onChange(nextIds, networks, selected);
  };

  const toggle = (account: SocialAccountItem) => {
    const next = selectedIds.includes(account.id)
      ? selectedIds.filter((id) => id !== account.id)
      : [...selectedIds, account.id];
    emitChange(next);
  };

  const toggleNetwork = (network: Network) => {
    const networkAccounts = accounts.filter((a) => a.network === network);
    const allSelected = networkAccounts.every((a) => selectedIds.includes(a.id));
    let next: string[];
    if (allSelected) {
      const networkIds = new Set(networkAccounts.map((a) => a.id));
      next = selectedIds.filter((id) => !networkIds.has(id));
    } else {
      const existing = new Set(selectedIds);
      for (const a of networkAccounts) existing.add(a.id);
      next = [...existing];
    }
    emitChange(next);
  };

  if (loading) {
    return (
      <div className="space-y-3">
        {[1, 2].map((i) => (
          <div key={i} className="h-10 w-48 rounded-lg bg-gray-100 animate-pulse" />
        ))}
      </div>
    );
  }

  if (accounts.length === 0) {
    return (
      <div className="rounded-lg border border-dashed border-gray-300 bg-gray-50 px-4 py-6 text-center">
        <p className="text-sm text-gray-500">No connected accounts.</p>
        <a
          href="/dashboard/settings"
          className="mt-1 inline-block text-sm font-medium text-blue-600 hover:underline"
        >
          Connect an account in Settings &rarr;
        </a>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {grouped.map(({ network, accounts: networkAccounts, connected }) => {
        const Icon = NETWORK_ICON[network];
        const color = NETWORK_COLOR[network];
        const allSelected = networkAccounts.every((a) => selectedIds.includes(a.id));
        const someSelected = networkAccounts.some((a) => selectedIds.includes(a.id));

        return (
          <div key={network} className="space-y-1.5">
            {/* Network header — clickable to select/deselect all accounts in network */}
            <button
              type="button"
              onClick={() => connected && toggleNetwork(network)}
              disabled={!connected}
              className={`flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide transition-colors min-h-[44px] sm:min-h-0 ${
                connected ? "text-gray-500 hover:text-gray-700" : "text-gray-300 cursor-not-allowed"
              }`}
            >
              <Icon className="h-3.5 w-3.5" style={{ color: connected ? color : "#D1D5DB" }} />
              <span>{NETWORK_LABEL[network]}</span>
              {!connected && (
                <span className="text-[10px] font-normal text-gray-300 ml-0.5">(not connected)</span>
              )}
              {connected && networkAccounts.length > 1 && (
                <span className="text-[10px] font-normal text-gray-400 ml-0.5">
                  ({allSelected ? "deselect all" : someSelected ? "select all" : "select all"})
                </span>
              )}
            </button>

            {/* Account buttons or placeholder */}
            <div className="flex flex-wrap gap-2">
              {connected ? networkAccounts.map((account) => {
                const isSelected = selectedIds.includes(account.id);
                return (
                  <button
                    key={account.id}
                    type="button"
                    onClick={() => toggle(account)}
                    className={`flex items-center gap-2 rounded-lg border px-3 py-2.5 sm:py-2 min-h-[44px] sm:min-h-0 text-sm transition-all ${
                      isSelected
                        ? "border-primary bg-primary/5 font-medium shadow-sm"
                        : "border-gray-200 hover:border-gray-300 hover:bg-gray-50"
                    }`}
                  >
                    {account.avatarUrl ? (
                      <img src={account.avatarUrl} alt="" className="h-5 w-5 rounded-full" />
                    ) : (
                      <span
                        className="flex h-5 w-5 items-center justify-center rounded-full text-white"
                        style={{ backgroundColor: color }}
                      >
                        <Icon className="h-3 w-3" />
                      </span>
                    )}
                    <span className={isSelected ? "text-gray-900" : "text-gray-600"}>
                      {account.accountName.startsWith("@") ? account.accountName : `@${account.accountName}`}
                    </span>
                    {isSelected && (
                      <span className="ml-0.5 flex h-4 w-4 items-center justify-center rounded-full bg-green-500 text-white">
                        <svg className="h-2.5 w-2.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}>
                          <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                        </svg>
                      </span>
                    )}
                  </button>
                );
              }) : (
                <a
                  href="/dashboard/settings"
                  className="flex items-center gap-2 rounded-lg border border-dashed border-gray-200 px-3 py-2.5 sm:py-2 min-h-[44px] sm:min-h-0 text-sm text-gray-400 hover:text-gray-500 hover:border-gray-300 transition-all"
                >
                  <Icon className="h-4 w-4" />
                  <span>Connect {NETWORK_LABEL[network]}</span>
                </a>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}
