import { useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '../../lib/api';
import type { Glossary } from '../../types/api';
import {
  useClient,
  useTeams, useCreateTeam, useUpdateTeam, useDeleteTeam,
  useAddTeamMember, useRemoveTeamMember,
  useProjects, useCreateProject, useUpdateProject, useArchiveProject,
  usePMs, useAssignPM, useRemovePM,
} from '../../hooks/useClients';
import { useUsers } from '../../hooks/useUsers';
import { useAuthStore } from '../../lib/auth';
import { useToastContext } from '../../contexts/ToastContext';
import type { Team, Project } from '../../types/api';

export function ClientDetail() {
  const { clientId } = useParams<{ clientId: string }>();
  const { user } = useAuthStore();
  const toast = useToastContext();
  const isAdmin = user?.role === 'admin';

  const { data: client, isLoading: clientLoading } = useClient(clientId!);
  const { data: teams = [] } = useTeams(clientId!);
  const { data: projects = [] } = useProjects(clientId!);
  const { data: pms = [] } = usePMs(clientId!);
  const { data: usersResp } = useUsers({ size: 200, active_only: true });
  const allUsers = usersResp?.users ?? [];

  const createTeam = useCreateTeam(clientId!);
  const updateTeam = useUpdateTeam(clientId!);
  const deleteTeam = useDeleteTeam(clientId!);
  const addMember = useAddTeamMember(clientId!);
  const removeMember = useRemoveTeamMember(clientId!);

  const createProject = useCreateProject(clientId!);
  const updateProject = useUpdateProject(clientId!);
  const archiveProject = useArchiveProject(clientId!);

  const assignPM = useAssignPM(clientId!);
  const removePM = useRemovePM(clientId!);

  // UI state
  const [newTeamName, setNewTeamName] = useState('');
  const [editingTeam, setEditingTeam] = useState<Team | null>(null);
  const [expandedTeam, setExpandedTeam] = useState<string | null>(null);
  const [addMemberTeamId, setAddMemberTeamId] = useState<string | null>(null);
  const [selectedMemberUserId, setSelectedMemberUserId] = useState('');

  const [newProjectName, setNewProjectName] = useState('');
  const [editingProject, setEditingProject] = useState<Project | null>(null);

  const [pmUserId, setPmUserId] = useState('');

  const { data: glossaries = [] } = useQuery<Glossary[]>({
    queryKey: ['glossaries', clientId],
    queryFn: () => apiClient.getGlossaries(clientId!),
    enabled: !!clientId,
  });

  if (clientLoading) {
    return <div className="container mx-auto px-4 py-8 animate-pulse"><div className="h-8 bg-gray-200 rounded w-1/3" /></div>;
  }
  if (!client) {
    return <div className="container mx-auto px-4 py-8 text-red-500">Client not found</div>;
  }

  const pmUserIds = new Set(pms.map(p => p.id));

  const handleCreateTeam = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newTeamName.trim()) return;
    try {
      await createTeam.mutateAsync({ name: newTeamName.trim() });
      setNewTeamName('');
      toast.success('Team created');
    } catch { toast.error('Failed to create team'); }
  };

  const handleCreateProject = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newProjectName.trim()) return;
    try {
      await createProject.mutateAsync({ name: newProjectName.trim() });
      setNewProjectName('');
      toast.success('Project created');
    } catch { toast.error('Failed to create project'); }
  };

  const handleAssignPM = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!pmUserId) return;
    try {
      await assignPM.mutateAsync(pmUserId);
      setPmUserId('');
      toast.success('PM assigned');
    } catch { toast.error('Failed to assign PM'); }
  };

  return (
    <div className="container mx-auto px-4 py-8 max-w-5xl space-y-8">
      {/* Header */}
      <div>
        <p className="text-sm text-gray-400 mb-1">← <a href="/admin/clients" className="hover:text-blue-600">Clients</a></p>
        <h1 className="text-2xl font-bold text-gray-900">{client.name}</h1>
        <p className="text-xs text-gray-400 font-mono mt-0.5">{client.slug}</p>
      </div>

      {/* Project Managers (admin only) */}
      {isAdmin && (
        <section className="bg-white rounded-xl border border-gray-200 p-5">
          <h2 className="text-base font-semibold text-gray-800 mb-4">Project Managers</h2>
          <div className="space-y-2 mb-4">
            {pms.length === 0 && <p className="text-sm text-gray-400">No PMs assigned</p>}
            {pms.map(pm => (
              <div key={pm.id} className="flex items-center justify-between py-2 px-3 bg-gray-50 rounded-lg">
                <div>
                  <p className="text-sm font-medium text-gray-800">{pm.full_name}</p>
                  <p className="text-xs text-gray-400">{pm.email}</p>
                </div>
                <button
                  onClick={async () => {
                    await removePM.mutateAsync(pm.id);
                    toast.success('PM removed');
                  }}
                  className="text-xs text-red-500 hover:text-red-700"
                >
                  Remove
                </button>
              </div>
            ))}
          </div>
          <form onSubmit={handleAssignPM} className="flex gap-2">
            <select
              value={pmUserId}
              onChange={e => setPmUserId(e.target.value)}
              className="flex-1 border border-gray-300 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">Select user to assign as PM…</option>
              {allUsers.filter(u => !pmUserIds.has(u.id)).map(u => (
                <option key={u.id} value={u.id}>{u.full_name} ({u.email})</option>
              ))}
            </select>
            <button
              type="submit"
              disabled={!pmUserId || assignPM.isPending}
              className="px-4 py-1.5 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 disabled:opacity-50"
            >
              Assign
            </button>
          </form>
        </section>
      )}

      {/* Teams */}
      <section className="bg-white rounded-xl border border-gray-200 p-5">
        <h2 className="text-base font-semibold text-gray-800 mb-4">Teams</h2>
        <div className="space-y-3 mb-4">
          {teams.length === 0 && <p className="text-sm text-gray-400">No teams yet</p>}
          {teams.map(team => (
            <div key={team.id} className="border border-gray-200 rounded-lg overflow-hidden">
              <div
                className="flex items-center justify-between p-3 cursor-pointer hover:bg-gray-50"
                onClick={() => setExpandedTeam(expandedTeam === team.id ? null : team.id)}
              >
                <div className="flex items-center gap-2">
                  <span className="text-sm font-medium text-gray-800">{team.name}</span>
                  <span className="text-xs text-gray-400 bg-gray-100 px-2 py-0.5 rounded-full">
                    {team.member_user_ids.length} members
                  </span>
                </div>
                <div className="flex items-center gap-2" onClick={e => e.stopPropagation()}>
                  <button
                    onClick={() => setEditingTeam(team)}
                    className="text-xs text-gray-500 hover:text-blue-600"
                  >
                    Rename
                  </button>
                  <button
                    onClick={async () => {
                      if (!confirm(`Delete team "${team.name}"?`)) return;
                      await deleteTeam.mutateAsync(team.id);
                      toast.success('Team deleted');
                    }}
                    className="text-xs text-red-500 hover:text-red-700"
                  >
                    Delete
                  </button>
                  <span className="text-gray-400">{expandedTeam === team.id ? '▲' : '▼'}</span>
                </div>
              </div>
              {expandedTeam === team.id && (
                <div className="border-t border-gray-100 p-3 bg-gray-50">
                  <div className="space-y-1.5 mb-3">
                    {team.member_user_ids.length === 0 && (
                      <p className="text-xs text-gray-400">No members</p>
                    )}
                    {team.member_user_ids.map(uid => {
                      const u = allUsers.find(u => u.id === uid);
                      return (
                        <div key={uid} className="flex items-center justify-between text-sm">
                          <span className="text-gray-700">{u ? `${u.full_name} (${u.email})` : uid}</span>
                          <button
                            onClick={async () => {
                              await removeMember.mutateAsync({ teamId: team.id, userId: uid });
                              toast.success('Member removed');
                            }}
                            className="text-xs text-red-500 hover:text-red-700"
                          >
                            ×
                          </button>
                        </div>
                      );
                    })}
                  </div>
                  {addMemberTeamId === team.id ? (
                    <div className="flex gap-2">
                      <select
                        value={selectedMemberUserId}
                        onChange={e => setSelectedMemberUserId(e.target.value)}
                        className="flex-1 border border-gray-300 rounded px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-blue-500"
                      >
                        <option value="">Select user…</option>
                        {allUsers.filter(u => !team.member_user_ids.includes(u.id)).map(u => (
                          <option key={u.id} value={u.id}>{u.full_name} ({u.email})</option>
                        ))}
                      </select>
                      <button
                        disabled={!selectedMemberUserId}
                        onClick={async () => {
                          await addMember.mutateAsync({ teamId: team.id, userId: selectedMemberUserId });
                          setSelectedMemberUserId('');
                          setAddMemberTeamId(null);
                          toast.success('Member added');
                        }}
                        className="px-3 py-1 bg-blue-600 text-white text-xs rounded hover:bg-blue-700 disabled:opacity-50"
                      >
                        Add
                      </button>
                      <button onClick={() => setAddMemberTeamId(null)} className="text-xs text-gray-500">Cancel</button>
                    </div>
                  ) : (
                    <button
                      onClick={() => { setAddMemberTeamId(team.id); setSelectedMemberUserId(''); }}
                      className="text-xs text-blue-600 hover:text-blue-800"
                    >
                      + Add member
                    </button>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
        <form onSubmit={handleCreateTeam} className="flex gap-2">
          <input
            type="text"
            value={newTeamName}
            onChange={e => setNewTeamName(e.target.value)}
            placeholder="New team name…"
            className="flex-1 border border-gray-300 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
          <button
            type="submit"
            disabled={!newTeamName.trim() || createTeam.isPending}
            className="px-4 py-1.5 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 disabled:opacity-50"
          >
            + Team
          </button>
        </form>
      </section>

      {/* Projects */}
      <section className="bg-white rounded-xl border border-gray-200 p-5">
        <h2 className="text-base font-semibold text-gray-800 mb-4">Projects</h2>
        <div className="space-y-2 mb-4">
          {projects.length === 0 && <p className="text-sm text-gray-400">No projects yet</p>}
          {projects.map(project => (
            <div key={project.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
              {editingProject?.id === project.id ? (
                <form
                  className="flex gap-2 flex-1"
                  onSubmit={async e => {
                    e.preventDefault();
                    await updateProject.mutateAsync({ projectId: project.id, data: { name: editingProject.name } });
                    setEditingProject(null);
                    toast.success('Project updated');
                  }}
                >
                  <input
                    type="text"
                    value={editingProject.name}
                    onChange={e => setEditingProject({ ...editingProject, name: e.target.value })}
                    className="flex-1 border border-gray-300 rounded px-2 py-1 text-sm"
                    autoFocus
                  />
                  <button type="submit" className="text-xs text-blue-600">Save</button>
                  <button type="button" onClick={() => setEditingProject(null)} className="text-xs text-gray-500">Cancel</button>
                </form>
              ) : (
                <>
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-gray-800">{project.name}</span>
                    {!project.is_active && (
                      <span className="text-xs bg-gray-200 text-gray-500 px-2 py-0.5 rounded-full">Archived</span>
                    )}
                  </div>
                  <div className="flex items-center gap-3">
                    <button onClick={() => setEditingProject(project)} className="text-xs text-gray-500 hover:text-blue-600">
                      Rename
                    </button>
                    {project.is_active && (
                      <button
                        onClick={async () => {
                          if (!confirm(`Archive project "${project.name}"?`)) return;
                          await archiveProject.mutateAsync(project.id);
                          toast.success('Project archived');
                        }}
                        className="text-xs text-red-500 hover:text-red-700"
                      >
                        Archive
                      </button>
                    )}
                  </div>
                </>
              )}
            </div>
          ))}
        </div>
        <form onSubmit={handleCreateProject} className="flex gap-2">
          <input
            type="text"
            value={newProjectName}
            onChange={e => setNewProjectName(e.target.value)}
            placeholder="New project name…"
            className="flex-1 border border-gray-300 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
          <button
            type="submit"
            disabled={!newProjectName.trim() || createProject.isPending}
            className="px-4 py-1.5 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 disabled:opacity-50"
          >
            + Project
          </button>
        </form>
      </section>

      {/* Glossaries */}
      <section className="bg-white rounded-xl border border-gray-200 p-5">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-base font-semibold text-gray-800">Glossaries</h2>
          <Link
            to={`/admin/clients/${clientId}/glossaries`}
            className="text-sm text-blue-600 hover:text-blue-700"
          >
            View all →
          </Link>
        </div>
        {glossaries.length === 0 ? (
          <p className="text-sm text-gray-400">No glossaries yet</p>
        ) : (
          <div className="space-y-2">
            {glossaries.slice(0, 3).map(g => (
              <div key={g.id} className="flex items-center justify-between py-1.5">
                <Link
                  to={`/admin/clients/${clientId}/glossaries/${g.id}`}
                  className="text-sm text-gray-800 hover:text-blue-600"
                >
                  {g.name}
                </Link>
                <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                  g.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
                }`}>
                  {g.status}
                </span>
              </div>
            ))}
            {glossaries.length > 3 && (
              <p className="text-xs text-gray-400">+{glossaries.length - 3} more</p>
            )}
          </div>
        )}
        {(isAdmin || user?.role === 'project_manager') && (
          <div className="mt-4">
            <Link
              to={`/admin/clients/${clientId}/glossaries/upload`}
              className="text-sm text-blue-600 hover:underline"
            >
              + Upload glossary
            </Link>
          </div>
        )}
      </section>

      {/* Rename team modal */}
      {editingTeam && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <form
            className="bg-white rounded-xl p-6 w-full max-w-sm shadow-xl"
            onSubmit={async e => {
              e.preventDefault();
              await updateTeam.mutateAsync({ teamId: editingTeam.id, name: editingTeam.name });
              setEditingTeam(null);
              toast.success('Team renamed');
            }}
          >
            <h3 className="text-base font-semibold mb-4">Rename Team</h3>
            <input
              type="text"
              value={editingTeam.name}
              onChange={e => setEditingTeam({ ...editingTeam, name: e.target.value })}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm mb-4 focus:outline-none focus:ring-2 focus:ring-blue-500"
              autoFocus
            />
            <div className="flex gap-3">
              <button type="button" onClick={() => setEditingTeam(null)} className="flex-1 border border-gray-300 text-sm rounded-lg px-4 py-2 hover:bg-gray-50">Cancel</button>
              <button type="submit" className="flex-1 bg-blue-600 text-white text-sm rounded-lg px-4 py-2 hover:bg-blue-700">Save</button>
            </div>
          </form>
        </div>
      )}
    </div>
  );
}
