'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { createUserSchema, type CreateUserInput } from '@vihar/shared';
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';

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

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, '');
}

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

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 }: { checked: boolean; onChange: (v: boolean) => void; label: string }) {
  return (
    <button type="button" onClick={() => onChange(!checked)} className="flex items-center justify-between py-1 w-full">
      <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>
  );
}

// ---- Credential sheet after save -----------------------------------------

function CredentialSheet({
  user,
  password,
  phone,
  captainName,
  onDone,
}: {
  user: { fullName: string; username: string };
  password: string;
  phone: string;
  captainName: string;
  onDone: () => void;
}) {
  const [copied, setCopied] = useState<'msg' | 'pwd' | null>(null);
  const [tpl, setTpl] = useState<CredentialsTemplate | null>(null);
  const [tplError, setTplError] = useState<string | null>(null);

  useEffect(() => {
    api.get<CredentialsTemplate>('/api/templates/volunteer_credentials')
      .then(setTpl)
      .catch((e) => setTplError(e instanceof ApiError ? e.message : 'Failed to load template'));
  }, []);

  const loginUrl = (typeof process !== 'undefined' && process.env.NEXT_PUBLIC_SITE_URL)
    || (typeof window !== 'undefined' ? window.location.origin : '');

  const message = tpl
    ? renderTemplate(tpl.body, {
        full_name: user.fullName,
        username: user.username,
        password,
        phone,
        login_url: loginUrl,
        city_name: tpl.cityName,
        captain_name: captainName,
      })
    : '';

  const waUrl = message ? `https://wa.me/91${digitsOnly(phone)}?text=${encodeURIComponent(message)}` : '#';

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

  return (
    <div className="space-y-4">
      <div>
        <h1 className="font-display text-2xl font-semibold text-ink">Volunteer Added</h1>
        <p className="mt-0.5 text-sm text-ink-300">Share credentials with {user.fullName}</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">{user.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">Initial password</p>
              <p className="text-sm font-mono text-ink">{password}</p>
            </div>
            <Button variant="outline" className="h-8 px-2 text-xs" onClick={() => copy(password, 'pwd')}>
              {copied === 'pwd' ? '✓' : 'Copy'}
            </Button>
          </div>
        </CardContent>
      </Card>

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

      {tpl && (
        <div>
          <p className="mb-1 text-xs font-medium uppercase tracking-wide text-ink-300">Message preview</p>
          <pre className="max-h-56 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">
            {message}
          </pre>
        </div>
      )}

      <a
        href={waUrl}
        rel="noopener"
        target="_blank"
        aria-disabled={!message}
        className={`flex w-full items-center justify-center gap-2 rounded-md py-3 text-sm font-semibold text-white ${message ? 'bg-[#25D366]' : 'bg-paper-300 pointer-events-none'}`}
      >
        <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" disabled={!message} onClick={() => copy(message, 'msg')}>
          {copied === 'msg' ? '✓ Copied' : 'Copy message'}
        </Button>
        <Button className="flex-1" onClick={onDone}>Done</Button>
      </div>
    </div>
  );
}

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

export default function NewVolunteerPage() {
  const router = useRouter();
  const { data: me } = useMe();
  const [localities, setLocalities] = useState<Locality[]>([]);
  const [generatedPassword, setGeneratedPassword] = useState('');
  const [saved, setSaved] = useState<{ fullName: string; username: string; phone: string } | null>(null);

  const {
    register,
    handleSubmit,
    control,
    watch,
    setValue,
    formState: { errors, isSubmitting },
    setError,
  } = useForm<CreateUserInput>({
    resolver: zodResolver(createUserSchema),
    defaultValues: {
      isCaptain: false,
      isVolunteer: true,
      homeLocalityId: null,
    },
  });

  const isCaptain = watch('isCaptain');

  useEffect(() => {
    api.get<Locality[]>('/api/localities').then(setLocalities).catch(() => {});
    const pwd = generatePassword();
    setGeneratedPassword(pwd);
    setValue('initialPassword', pwd);
  }, [setValue]);

  function refreshPassword() {
    const pwd = generatePassword();
    setGeneratedPassword(pwd);
    setValue('initialPassword', pwd);
  }

  async function onSubmit(data: CreateUserInput) {
    try {
      await api.post('/api/users', data);
      setSaved({ fullName: data.fullName, username: data.username, phone: data.phone });
    } catch (e) {
      if (e instanceof ApiError && e.status === 409) {
        const msg = e.message.toLowerCase();
        if (msg.includes('username')) setError('username', { message: 'Username already taken' });
        else if (msg.includes('phone')) setError('phone', { message: 'Phone already registered' });
        else setError('root', { message: e.message });
      } else {
        setError('root', { message: e instanceof ApiError ? e.message : 'Failed to create' });
      }
    }
  }

  if (saved) {
    return (
      <CredentialSheet
        user={saved}
        password={generatedPassword}
        phone={saved.phone}
        captainName={me?.fullName ?? 'your captain'}
        onDone={() => router.push('/captain/volunteers')}
      />
    );
  }

  return (
    <div className="space-y-5 pb-24">
      <div>
        <h1 className="font-display text-2xl font-semibold text-ink">Add Volunteer</h1>
        <div className="mt-1 h-0.5 w-12 bg-saffron rounded-full" />
      </div>

      <form onSubmit={handleSubmit(onSubmit)} noValidate className="space-y-4">

        <Card>
          <CardHeader className="pb-2"><CardTitle className="text-base">Identity</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label className="mb-1.5 block text-sm">Full name <span className="text-rust">*</span></Label>
              <Input {...register('fullName')} placeholder="Rajesh Mehta" />
              {errors.fullName && <p className="mt-1 text-xs text-rust">{errors.fullName.message}</p>}
            </div>
            <div>
              <Label className="mb-1.5 block text-sm">Phone <span className="text-rust">*</span></Label>
              <Input {...register('phone')} type="tel" inputMode="numeric" placeholder="9876543210" maxLength={10} />
              {errors.phone && <p className="mt-1 text-xs text-rust">{errors.phone.message}</p>}
            </div>
            <div>
              <Label className="mb-1.5 block text-sm">Gender <span className="text-rust">*</span></Label>
              <Controller
                name="gender"
                control={control}
                render={({ field: f }) => (
                  <div className="flex gap-2">
                    {(['male', 'female'] as const).map((g) => (
                      <button
                        key={g}
                        type="button"
                        onClick={() => f.onChange(g)}
                        className={`flex-1 rounded-md border px-3 py-2 text-sm font-medium capitalize transition-colors ${
                          f.value === g
                            ? 'border-saffron bg-saffron/10 text-saffron-700'
                            : 'border-paper-300 bg-white text-ink-400 hover:bg-paper-50'
                        }`}
                      >
                        {g}
                      </button>
                    ))}
                  </div>
                )}
              />
              {errors.gender && <p className="mt-1 text-xs text-rust">Please select a gender</p>}
            </div>
            <div>
              <Label className="mb-1.5 block text-sm">Username <span className="text-rust">*</span></Label>
              <Input {...register('username')} placeholder="rajesh.m" autoCapitalize="none" />
              {errors.username && <p className="mt-1 text-xs text-rust">{errors.username.message}</p>}
            </div>
            <div>
              <Label className="mb-1.5 block text-sm">Home locality</Label>
              <Controller
                name="homeLocalityId"
                control={control}
                render={({ field: f }) => (
                  <select
                    value={f.value ?? ''}
                    onChange={(e) => f.onChange(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>

        <Card>
          <CardHeader className="pb-2"><CardTitle className="text-base">Roles</CardTitle></CardHeader>
          <CardContent className="space-y-1">
            <Controller
              name="isVolunteer"
              control={control}
              render={({ field: f }) => (
                <Toggle checked={f.value} onChange={f.onChange} label="Volunteer" />
              )}
            />
            <div className="h-px bg-paper-200" />
            <Controller
              name="isCaptain"
              control={control}
              render={({ field: f }) => (
                <Toggle
                  checked={f.value}
                  onChange={(v) => {
                    if (v && !confirm('Make this person a captain? They will be able to plan vihars and manage volunteers.')) return;
                    f.onChange(v);
                  }}
                  label="Captain"
                />
              )}
            />
            {isCaptain && (
              <p className="text-xs text-amber-600 pt-1">This user will have captain access.</p>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2"><CardTitle className="text-base">Initial password</CardTitle></CardHeader>
          <CardContent className="space-y-2">
            <div className="flex gap-2">
              <Input
                {...register('initialPassword')}
                readOnly
                className="font-mono flex-1 bg-paper-100"
              />
              <Button type="button" variant="outline" onClick={refreshPassword}>↻</Button>
            </div>
            <p className="text-xs text-ink-300">Share this with the volunteer after saving.</p>
            {errors.initialPassword && <p className="mt-1 text-xs text-rust">{errors.initialPassword.message}</p>}
          </CardContent>
        </Card>

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

        <div className="flex gap-3">
          <Button type="button" variant="outline" className="flex-1" onClick={() => router.push('/captain/volunteers')}>
            Cancel
          </Button>
          <Button type="submit" className="flex-1" disabled={isSubmitting}>
            {isSubmitting ? 'Saving…' : 'Add Volunteer'}
          </Button>
        </div>
      </form>
    </div>
  );
}
