'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { api, ApiError } from '@/lib/api';
import { useMe } from '@/lib/auth';
import { initials } from '@/lib/formatters';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';

// ---- Types ----------------------------------------------------------------

interface Volunteer {
  userId: number;
  fullName: string;
  username: string;
  phone: string;
  isCaptain: boolean;
  isVolunteer: boolean;
  isActive: boolean;
  homeLocality?: { localityId: number; name: string } | null;
  lifetimeViharCount: number;
  thisMonthViharCount: number;
}

interface Locality { localityId: number; name: string }
interface ListResponse { items: Volunteer[]; total: number }

type RoleFilter = 'all' | 'captain' | 'volunteer' | 'inactive';

interface CredentialsTemplate { templateKey: string; body: string; cityName: string }

interface CredentialsResult { fullName: string; phone: string; username: string; password: string; message: string; waUrl: string }

const PWD_CHARS = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';

function generatePassword(): string {
  const bytes = new Uint8Array(10);
  crypto.getRandomValues(bytes);
  return Array.from(bytes).map((b) => PWD_CHARS[b % PWD_CHARS.length]).join('');
}

function renderTemplate(body: string, vars: Record<string, string>): string {
  return body.replace(/\{\{(\w+)\}\}/g, (_, key) => vars[key] ?? `{{${key}}}`);
}

function digitsOnly(phone: string): string {
  return phone.replace(/\D/g, '');
}

// ---- Page -----------------------------------------------------------------

const ROLE_CHIPS: { label: string; value: RoleFilter }[] = [
  { label: 'All', value: 'all' },
  { label: 'Captains', value: 'captain' },
  { label: 'Volunteers', value: 'volunteer' },
  { label: 'Inactive', value: 'inactive' },
];

export default function VolunteersPage() {
  const router = useRouter();
  const { data: me } = useMe();
  const [search, setSearch] = useState('');
  const [localityId, setLocalityId] = useState<number | null>(null);
  const [roleFilter, setRoleFilter] = useState<RoleFilter>('all');
  const [credsBusy, setCredsBusy] = useState<number | null>(null);
  const [credsResult, setCredsResult] = useState<CredentialsResult | null>(null);
  const [credsError, setCredsError] = useState<string | null>(null);

  async function handleSendCredentials(vol: Volunteer) {
    if (credsBusy) return;
    if (!me) {
      setCredsError('Not signed in');
      return;
    }
    const ok = window.confirm(
      `This will reset ${vol.fullName}'s password to a new random value and prepare a WhatsApp message.\n\nContinue?`,
    );
    if (!ok) return;

    setCredsBusy(vol.userId);
    setCredsError(null);
    try {
      const newPassword = generatePassword();
      await api.post(`/api/users/${vol.userId}/reset-password`, { password: newPassword });
      const tpl = await api.get<CredentialsTemplate>('/api/templates/volunteer_credentials');
      const loginUrl = process.env.NEXT_PUBLIC_SITE_URL ?? window.location.origin;
      const message = renderTemplate(tpl.body, {
        full_name: vol.fullName,
        username: vol.username,
        password: newPassword,
        phone: vol.phone,
        login_url: loginUrl,
        city_name: tpl.cityName,
        captain_name: me.fullName,
      });
      const waUrl = `https://wa.me/91${digitsOnly(vol.phone)}?text=${encodeURIComponent(message)}`;
      setCredsResult({
        fullName: vol.fullName,
        phone: vol.phone,
        username: vol.username,
        password: newPassword,
        message,
        waUrl,
      });
    } catch (e) {
      setCredsError(e instanceof ApiError ? e.message : 'Failed to prepare credentials');
    } finally {
      setCredsBusy(null);
    }
  }

  const queryParams = {
    q: search || undefined,
    localityId: localityId ?? undefined,
    role: roleFilter === 'inactive' || roleFilter === 'all' ? undefined : roleFilter,
    isActive: roleFilter === 'inactive' ? false : undefined,
    pageSize: 100,
  };

  const { data, isLoading } = useQuery<ListResponse>({
    queryKey: ['volunteers', queryParams],
    queryFn: () => api.get<ListResponse>('/api/users', { query: queryParams }),
    placeholderData: (prev: ListResponse | undefined) => prev,
  });

  const { data: localities } = useQuery<Locality[]>({
    queryKey: ['localities'],
    queryFn: () => api.get<Locality[]>('/api/localities'),
    staleTime: Infinity,
  });

  return (
    <div className="space-y-4 pb-24">
      <div>
        <h1 className="font-display text-2xl font-semibold text-ink">Vihar Sevaks</h1>
        {data && <p className="mt-0.5 text-sm text-ink-300">{data.total} member{data.total !== 1 ? 's' : ''}</p>}
      </div>

      {/* Filters */}
      <div className="flex gap-2">
        <Input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search by name or phone…"
          className="flex-1"
        />
        {localities && localities.length > 0 && (
          <select
            value={localityId ?? ''}
            onChange={(e) => setLocalityId(e.target.value ? Number(e.target.value) : null)}
            className="rounded-md border border-paper-300 bg-white px-2 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-saffron"
          >
            <option value="">All localities</option>
            {localities.map((l) => (
              <option key={l.localityId} value={l.localityId}>{l.name}</option>
            ))}
          </select>
        )}
      </div>

      {/* Role chips */}
      <div className="flex flex-wrap gap-2">
        {ROLE_CHIPS.map(({ label, value }) => (
          <button
            key={value}
            onClick={() => setRoleFilter(value)}
            className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
              roleFilter === value ? 'bg-ink text-paper' : 'bg-paper-200 text-ink-400 hover:bg-paper-300'
            }`}
          >
            {label}
          </button>
        ))}
      </div>

      {isLoading && <p className="py-8 text-center text-sm text-ink-300">Loading…</p>}

      {data && data.items.length === 0 && (
        <Card>
          <CardContent className="py-10 text-center text-sm text-ink-300">
            No members match your filters.
          </CardContent>
        </Card>
      )}

      {data && data.items.length > 0 && (
        <div className="space-y-2">
          {data.items.map((vol) => {
            const phoneDigits = digitsOnly(vol.phone);
            const isBusy = credsBusy === vol.userId;
            return (
              <div
                key={vol.userId}
                className="flex items-center gap-2 rounded-lg border border-paper-200 bg-white px-3 py-3 transition-colors hover:bg-paper-50"
              >
                <button
                  type="button"
                  onClick={() => router.push(`/captain/volunteers/${vol.userId}`)}
                  className="flex flex-1 min-w-0 items-center gap-3 text-left"
                >
                  <div className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-sm font-semibold ${
                    vol.isActive ? 'bg-saffron-100 text-saffron-700' : 'bg-paper-200 text-ink-300'
                  }`}>
                    {initials(vol.fullName)}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-1.5">
                      <p className={`text-sm font-medium truncate ${vol.isActive ? 'text-ink' : 'text-ink-300 line-through'}`}>
                        {vol.fullName}
                      </p>
                      {vol.isCaptain && (
                        <span className="shrink-0 rounded bg-ink-100 px-1.5 py-0.5 text-[10px] font-medium text-ink-500">Captain</span>
                      )}
                    </div>
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="text-xs text-ink-300">{vol.phone}</span>
                      {vol.homeLocality && (
                        <>
                          <span className="text-ink-200 text-xs">·</span>
                          <span className="text-xs text-ink-300">{vol.homeLocality.name}</span>
                        </>
                      )}
                      <span className="text-ink-200 text-xs">·</span>
                      <span className="text-xs text-ink-300">{vol.lifetimeViharCount} vihars</span>
                    </div>
                  </div>
                </button>

                <div className="flex shrink-0 items-center gap-1">
                  <a
                    href={`tel:${phoneDigits}`}
                    title={`Call ${vol.fullName}`}
                    aria-label={`Call ${vol.fullName}`}
                    onClick={(e) => e.stopPropagation()}
                    className="flex h-9 w-9 items-center justify-center rounded-full bg-paper-100 text-ink-500 hover:bg-paper-200"
                  >
                    <svg viewBox="0 0 24 24" fill="currentColor" className="h-4 w-4">
                      <path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57a1 1 0 0 0-1.02.24l-2.2 2.2a15.05 15.05 0 0 1-6.59-6.59l2.2-2.2a1 1 0 0 0 .25-1.02A11.36 11.36 0 0 1 8.5 4a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1c0 9.39 7.61 17 17 17a1 1 0 0 0 1-1v-3.5a1 1 0 0 0-1-1z" />
                    </svg>
                  </a>
                  <a
                    href={`https://wa.me/91${phoneDigits}`}
                    target="_blank"
                    rel="noopener"
                    title={`WhatsApp ${vol.fullName}`}
                    aria-label={`WhatsApp ${vol.fullName}`}
                    onClick={(e) => e.stopPropagation()}
                    className="flex h-9 w-9 items-center justify-center rounded-full bg-[#25D366]/10 text-[#1da851] hover:bg-[#25D366]/20"
                  >
                    <svg viewBox="0 0 24 24" fill="currentColor" className="h-4 w-4">
                      <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z" />
                    </svg>
                  </a>
                  <button
                    type="button"
                    onClick={(e) => { e.stopPropagation(); handleSendCredentials(vol); }}
                    disabled={isBusy}
                    title="Reset password and share credentials"
                    aria-label={`Send credentials to ${vol.fullName}`}
                    className="flex h-9 w-9 items-center justify-center rounded-full bg-saffron/10 text-saffron-700 hover:bg-saffron/20 disabled:opacity-60"
                  >
                    {isBusy ? (
                      <span className="h-3 w-3 animate-spin rounded-full border-2 border-saffron-700 border-t-transparent" />
                    ) : (
                      <svg viewBox="0 0 24 24" fill="currentColor" className="h-4 w-4">
                        <path d="M12.65 10A6 6 0 0 0 7 6a6 6 0 1 0 0 12 6 6 0 0 0 5.65-4H17v4h4v-4h2v-4H12.65zM7 14a2 2 0 1 1 0-4 2 2 0 0 1 0 4z" />
                      </svg>
                    )}
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {credsError && (
        <div className="fixed inset-x-3 bottom-24 z-20 rounded-md bg-red-50 px-3 py-2 text-sm text-rust shadow-md">
          {credsError}
          <button onClick={() => setCredsError(null)} className="ml-2 font-semibold">×</button>
        </div>
      )}

      {credsResult && (
        <CredentialsModal result={credsResult} onClose={() => setCredsResult(null)} />
      )}

      {/* FAB */}
      <div className="fixed bottom-20 right-4 z-10">
        <Button
          onClick={() => router.push('/captain/volunteers/new')}
          className="h-14 w-14 rounded-full text-xl shadow-lg"
        >
          +
        </Button>
      </div>
    </div>
  );
}

// ---- Credentials modal ----------------------------------------------------

function CredentialsModal({ result, onClose }: { result: CredentialsResult; onClose: () => void }) {
  const [copied, setCopied] = useState<'msg' | 'pwd' | null>(null);

  async function copy(value: string, kind: 'msg' | 'pwd') {
    await navigator.clipboard.writeText(value);
    setCopied(kind);
    setTimeout(() => setCopied(null), 2000);
  }

  return (
    <div className="fixed inset-0 z-30 flex items-end justify-center bg-black/40 sm:items-center" onClick={onClose}>
      <div
        className="w-full max-w-md space-y-4 rounded-t-xl bg-white p-4 shadow-xl sm:rounded-xl"
        onClick={(e) => e.stopPropagation()}
      >
        <div>
          <h2 className="font-display text-lg font-semibold text-ink">Credentials ready</h2>
          <p className="mt-0.5 text-sm text-ink-300">
            New password set for <span className="font-medium text-ink">{result.fullName}</span>.
            Share via WhatsApp now — this password is shown only once.
          </p>
        </div>

        <Card className="bg-moss-50 border-moss-200">
          <CardContent className="pt-4 space-y-2">
            <div>
              <p className="text-xs font-medium uppercase tracking-wide text-ink-300">Username</p>
              <p className="text-sm font-mono text-ink">{result.username}</p>
            </div>
            <div className="flex items-end justify-between gap-2">
              <div>
                <p className="text-xs font-medium uppercase tracking-wide text-ink-300">New password</p>
                <p className="text-sm font-mono text-ink">{result.password}</p>
              </div>
              <Button variant="outline" className="h-8 px-2 text-xs" onClick={() => copy(result.password, 'pwd')}>
                {copied === 'pwd' ? '✓' : 'Copy'}
              </Button>
            </div>
          </CardContent>
        </Card>

        <div>
          <p className="mb-1 text-xs font-medium uppercase tracking-wide text-ink-300">Message preview</p>
          <pre className="max-h-48 overflow-y-auto whitespace-pre-wrap rounded-md border border-paper-200 bg-paper-50 p-2 font-mono text-xs leading-relaxed text-ink">
            {result.message}
          </pre>
        </div>

        <a
          href={result.waUrl}
          target="_blank"
          rel="noopener"
          className="flex w-full items-center justify-center gap-2 rounded-md bg-[#25D366] py-3 text-sm font-semibold text-white"
        >
          <svg viewBox="0 0 24 24" fill="currentColor" className="h-4 w-4">
            <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z" />
          </svg>
          Send via WhatsApp
        </a>

        <div className="flex gap-2">
          <Button variant="outline" className="flex-1" onClick={() => copy(result.message, 'msg')}>
            {copied === 'msg' ? '✓ Copied' : 'Copy message'}
          </Button>
          <Button variant="ghost" className="flex-1" onClick={onClose}>Done</Button>
        </div>
      </div>
    </div>
  );
}
