'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { api, ApiError } from '@/lib/api';
import { useMe } from '@/lib/auth';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';

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

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

interface Locality { localityId: number; name: string }

// ---- Helpers --------------------------------------------------------------

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

function Toggle({ checked, onChange, label, disabled }: {
  checked: boolean; onChange: (v: boolean) => void; label: string; disabled?: boolean;
}) {
  return (
    <button
      type="button"
      onClick={() => !disabled && onChange(!checked)}
      className={`flex items-center justify-between py-1 w-full ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
    >
      <span className="text-sm text-ink">{label}</span>
      <span className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${checked ? 'bg-saffron' : 'bg-paper-300'}`}>
        <span className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${checked ? 'translate-x-6' : 'translate-x-1'}`} />
      </span>
    </button>
  );
}

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

export default function VolunteerDetailPage() {
  const { id } = useParams<{ id: string }>();
  const userId = Number(id);
  const router = useRouter();
  const qc = useQueryClient();
  const { data: me } = useMe();

  const { data: user, isLoading, isError } = useQuery<VolunteerDetail>({
    queryKey: ['user', userId],
    queryFn: () => api.get<VolunteerDetail>(`/api/users/${userId}`),
  });

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

  const [editing, setEditing] = useState(false);
  const [fullName, setFullName] = useState('');
  const [homeLocalityId, setHomeLocalityId] = useState<number | null>(null);
  const [isCaptain, setIsCaptain] = useState(false);
  const [isVolunteer, setIsVolunteer] = useState(true);
  const [isActive, setIsActive] = useState(true);
  const [saveError, setSaveError] = useState('');
  const [saving, setSaving] = useState(false);

  const [resetPwd, setResetPwd] = useState<string | null>(null);
  const [resetCopied, setResetCopied] = useState(false);
  const [resetError, setResetError] = useState('');
  const [resetting, setResetting] = useState(false);

  useEffect(() => {
    if (user) {
      setFullName(user.fullName);
      setHomeLocalityId(user.homeLocality?.localityId ?? null);
      setIsCaptain(user.isCaptain);
      setIsVolunteer(user.isVolunteer);
      setIsActive(user.isActive);
    }
  }, [user]);

  async function handleSave() {
    setSaving(true); setSaveError('');
    try {
      await api.patch(`/api/users/${userId}`, {
        fullName,
        homeLocalityId: homeLocalityId ?? null,
        isCaptain,
        isVolunteer,
        isActive,
      });
      qc.invalidateQueries({ queryKey: ['user', userId] });
      qc.invalidateQueries({ queryKey: ['volunteers'] });
      setEditing(false);
    } catch (e) {
      setSaveError(e instanceof ApiError ? e.message : 'Failed to save');
    } finally {
      setSaving(false);
    }
  }

  async function handleResetPassword() {
    const pwd = generatePassword();
    setResetting(true); setResetError('');
    try {
      await api.post(`/api/users/${userId}/reset-password`, { password: pwd });
      setResetPwd(pwd);
      setResetCopied(false);
    } catch (e) {
      setResetError(e instanceof ApiError ? e.message : 'Failed to reset password');
    } finally {
      setResetting(false);
    }
  }

  async function copyReset() {
    if (!resetPwd || !user) return;
    await navigator.clipboard.writeText(`Username: ${user.username}\nPassword: ${resetPwd}`);
    setResetCopied(true);
    setTimeout(() => setResetCopied(false), 2000);
  }

  const isSelf = me?.userId === userId;

  if (isLoading) return <div className="py-20 text-center text-sm text-ink-300">Loading…</div>;
  if (isError || !user) return <div className="py-20 text-center text-sm text-rust">User not found.</div>;

  return (
    <div className="space-y-4 pb-24">
      <div className="flex items-start justify-between">
        <div>
          <h1 className="font-display text-2xl font-semibold text-ink">{user.fullName}</h1>
          <p className="mt-0.5 text-sm text-ink-300">@{user.username}</p>
        </div>
        <div className="flex gap-2">
          {!editing && (
            <Button variant="outline" size="sm" onClick={() => setEditing(true)}>Edit</Button>
          )}
          {editing && (
            <>
              <Button variant="outline" size="sm" onClick={() => { setEditing(false); setSaveError(''); }}>Cancel</Button>
              <Button size="sm" onClick={handleSave} disabled={saving}>{saving ? 'Saving…' : 'Save'}</Button>
            </>
          )}
        </div>
      </div>

      {/* Info card */}
      <Card>
        <CardContent className="space-y-4 pt-4">
          {editing ? (
            <div>
              <Label className="mb-1.5 block text-sm">Full name</Label>
              <Input value={fullName} onChange={(e) => setFullName(e.target.value)} />
            </div>
          ) : (
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div>
                <p className="text-xs font-medium uppercase tracking-wide text-ink-300">Phone</p>
                <p className="text-ink">{user.phone}</p>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-wide text-ink-300">Locality</p>
                <p className="text-ink">{user.homeLocality?.name ?? '—'}</p>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-wide text-ink-300">Status</p>
                <p className={user.isActive ? 'text-moss-600' : 'text-rust'}>
                  {user.isActive ? 'Active' : 'Inactive'}
                </p>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-wide text-ink-300">Roles</p>
                <p className="text-ink">
                  {[user.isVolunteer && 'Volunteer', user.isCaptain && 'Captain'].filter(Boolean).join(', ') || '—'}
                </p>
              </div>
            </div>
          )}

          {editing && (
            <>
              <div>
                <Label className="mb-1.5 block text-sm">Home locality</Label>
                <select
                  value={homeLocalityId ?? ''}
                  onChange={(e) => setHomeLocalityId(e.target.value ? Number(e.target.value) : null)}
                  className="w-full rounded-md border border-paper-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-saffron"
                >
                  <option value="">— none —</option>
                  {(localities ?? []).map((l) => (
                    <option key={l.localityId} value={l.localityId}>{l.name}</option>
                  ))}
                </select>
              </div>
            </>
          )}
        </CardContent>
      </Card>

      {/* Roles / active */}
      {editing && (
        <Card>
          <CardHeader className="pb-2"><CardTitle className="text-base">Roles & Status</CardTitle></CardHeader>
          <CardContent className="space-y-1">
            <Toggle checked={isVolunteer} onChange={setIsVolunteer} label="Volunteer" />
            <div className="h-px bg-paper-200" />
            <Toggle
              checked={isCaptain}
              onChange={(v) => {
                if (v && !confirm(`Make ${user.fullName} a captain? They will be able to plan vihars and manage volunteers.`)) return;
                setIsCaptain(v);
              }}
              label="Captain"
            />
            <div className="h-px bg-paper-200" />
            <Toggle
              checked={isActive}
              onChange={(v) => {
                if (!v && isSelf && !confirm('Deactivate yourself? You will be logged out.')) return;
                setIsActive(v);
              }}
              label="Active"
              disabled={isSelf}
            />
            {isSelf && !isActive && (
              <p className="text-xs text-rust">You cannot deactivate yourself.</p>
            )}
          </CardContent>
        </Card>
      )}

      {saveError && (
        <p className="rounded-md bg-red-50 px-3 py-2 text-sm text-rust">{saveError}</p>
      )}

      {/* Reset password */}
      <Card>
        <CardHeader className="pb-2"><CardTitle className="text-base">Password</CardTitle></CardHeader>
        <CardContent className="space-y-3">
          {resetPwd ? (
            <>
              <p className="text-xs text-ink-300">New password generated. Share with the volunteer:</p>
              <div className="rounded-md bg-paper-100 px-3 py-2 font-mono text-sm text-ink">{resetPwd}</div>
              <div className="flex gap-2">
                <Button variant="outline" className="flex-1" onClick={copyReset}>
                  {resetCopied ? '✓ Copied!' : 'Copy'}
                </Button>
                <a
                  href={`https://wa.me/91${user.phone}?text=${encodeURIComponent(`Your new Vihar Sewa password:\nUsername: ${user.username}\nPassword: ${resetPwd}`)}`}
                  rel="noopener"
                  className="flex flex-1 items-center justify-center gap-1 rounded-md bg-[#25D366] py-2 text-sm font-medium text-white"
                >
                  WhatsApp
                </a>
              </div>
              <Button variant="ghost" className="w-full text-xs text-ink-300" onClick={() => setResetPwd(null)}>
                Dismiss
              </Button>
            </>
          ) : (
            <>
              <p className="text-sm text-ink-300">Generate a new password and share with the volunteer.</p>
              {resetError && (
                <p className="rounded-md bg-red-50 px-3 py-2 text-sm text-rust">{resetError}</p>
              )}
              <Button variant="outline" className="w-full" onClick={handleResetPassword} disabled={resetting}>
                {resetting ? 'Generating…' : 'Generate new password'}
              </Button>
            </>
          )}
        </CardContent>
      </Card>

      <Button variant="ghost" className="w-full text-sm" onClick={() => router.push('/captain/volunteers')}>
        ← Back to list
      </Button>
    </div>
  );
}
