'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { apiFetchJson } from '@/lib/auth';
import { PageHeader } from '@/components/school/page-header';
import {
  FloatingOutlineDate,
  FloatingOutlineSelect,
  FloatingOutlineText,
  FloatingOutlineTextarea,
  OutlineFormCard,
  OutlinePhotoDropzone,
} from '@/components/school/floating-outline-fields';
import { useToast } from '@/components/school/toast-context';

function BreadcrumbChevron() {
  return (
    <svg className="stroke-current shrink-0 text-gray-400" width={17} height={16} viewBox="0 0 17 16" fill="none" aria-hidden>
      <path
        d="M6.0765 12.667L10.2432 8.50033L6.0765 4.33366"
        stroke="currentColor"
        strokeWidth={1.2}
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export default function NewTeacherPage() {
  const router = useRouter();
  const { toast } = useToast();
  const [form, setForm] = useState({
    firstName: '',
    lastName: '',
    gender: 'MALE',
    birthDate: '',
    phone: '',
    photoUrl: '',
    title: '',
    address: '',
    hireDate: '',
    isActive: true,
    password: '',
    email: '',
  });
  const [photoPreview, setPhotoPreview] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [tempPassword, setTempPassword] = useState('');

  const onPhotoChange = (file: File | undefined) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      const value = String(reader.result || '');
      setPhotoPreview(value);
      setForm((prev) => ({ ...prev, photoUrl: value }));
    };
    reader.readAsDataURL(file);
  };

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError('');
    setTempPassword('');

    const res = await apiFetchJson<{ tempPassword?: string; message?: string }>('/v1/admin/staff', {
      method: 'POST',
      body: JSON.stringify({
        fullName: `${form.firstName} ${form.lastName}`.trim(),
        email: form.email,
        phone: form.phone || undefined,
        photoUrl: form.photoUrl || undefined,
        title: form.title || undefined,
        address: form.address || undefined,
        birthDate: form.birthDate || undefined,
        hireDate: form.hireDate || undefined,
        isActive: form.isActive,
        password: form.password,
        gender: form.gender,
        role: 'TEACHER',
      }),
    });

    setSaving(false);

    if (res.error) {
      setError(res.error);
      toast({ title: 'Kayıt başarısız', description: res.error, variant: 'destructive' });
      return;
    }

    const data = (res.data ?? {}) as { tempPassword?: string };
    const tp = data.tempPassword ?? '';
    setTempPassword(tp);
    toast({
      title: 'Öğretmen oluşturuldu',
      description: tp ? `Geçici şifre: ${tp}` : 'Öğretmen listesine yönlendiriliyorsunuz.',
    });
    setTimeout(() => {
      router.push('/school/teachers');
    }, 1200);
  };

  return (
    <div className="space-y-6 font-urbanist">
      <PageHeader
        eyebrow="Personel"
        title="Yeni öğretmen"
        description="Profil ve personel bilgilerini tek adımda tamamlayın."
        backHref="/school/teachers"
      />

      <div className="mx-auto w-full max-w-[1536px] pb-20 md:pb-24">
        <div className="mb-6 flex flex-wrap items-center justify-end gap-3">
          <nav aria-label="Breadcrumb">
            <ol className="flex flex-wrap items-center gap-1.5">
              <li>
                <Link
                  href="/school/dashboard"
                  className="inline-flex items-center gap-1.5 text-sm text-gray-500 dark:text-gray-400"
                >
                  Panel
                  <BreadcrumbChevron />
                </Link>
              </li>
              <li>
                <Link
                  href="/school/teachers"
                  className="inline-flex items-center gap-1.5 text-sm text-gray-500 dark:text-gray-400"
                >
                  Öğretmenler
                  <BreadcrumbChevron />
                </Link>
              </li>
              <li className="text-sm text-gray-800 dark:text-white/90">Yeni öğretmen</li>
            </ol>
          </nav>
        </div>

        {error ? (
          <div
            role="alert"
            className="mb-6 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800 dark:border-red-900/50 dark:bg-red-950/40 dark:text-red-200"
          >
            {error}
          </div>
        ) : null}
        {tempPassword ? (
          <div
            role="status"
            className="mb-6 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800 dark:border-emerald-900/40 dark:bg-emerald-950/30 dark:text-emerald-200"
          >
            Öğretmen oluşturuldu. Geçici şifre:{' '}
            <span className="font-semibold tabular-nums">{tempPassword}</span>
          </div>
        ) : null}

        <form onSubmit={submit} className="space-y-4">
          <OutlineFormCard title="Kişisel bilgiler">
            <div className="flex flex-col gap-6 xl:flex-row">
              <div className="w-full shrink-0 xl:aspect-square xl:w-[376px]">
                <OutlinePhotoDropzone previewUrl={photoPreview} onFile={onPhotoChange} title="Öğretmen fotoğrafı" />
              </div>
              <div className="grid w-full min-w-0 grid-cols-1 gap-x-6 gap-y-4 lg:grid-cols-2">
                <FloatingOutlineText
                  id="teacher-fn"
                  label="Ad"
                  value={form.firstName}
                  onChange={(v) => setForm({ ...form, firstName: v })}
                  required
                  autoComplete="given-name"
                />
                <FloatingOutlineText
                  id="teacher-ln"
                  label="Soyad"
                  value={form.lastName}
                  onChange={(v) => setForm({ ...form, lastName: v })}
                  required
                  autoComplete="family-name"
                />
                <FloatingOutlineSelect
                  id="teacher-gender"
                  label="Cinsiyet"
                  value={form.gender}
                  onChange={(v) => setForm({ ...form, gender: v })}
                >
                  <option value="MALE">Erkek</option>
                  <option value="FEMALE">Kadın</option>
                </FloatingOutlineSelect>
                <FloatingOutlineDate
                  id="teacher-bd"
                  label="Doğum tarihi"
                  value={form.birthDate}
                  onChange={(v) => setForm({ ...form, birthDate: v })}
                />
                <div className="lg:col-span-2">
                  <FloatingOutlineText
                    id="teacher-phone"
                    label="GSM"
                    value={form.phone}
                    onChange={(v) => setForm({ ...form, phone: v })}
                    type="tel"
                    autoComplete="tel"
                  />
                </div>
              </div>
            </div>
          </OutlineFormCard>

          <OutlineFormCard title="İş ve adres">
            <div className="grid min-w-0 grid-cols-1 gap-x-6 gap-y-4 lg:grid-cols-2">
              <FloatingOutlineDate
                id="teacher-hire"
                label="Okula katılma tarihi"
                value={form.hireDate}
                onChange={(v) => setForm({ ...form, hireDate: v })}
              />
              <FloatingOutlineSelect
                id="teacher-status"
                label="Durum"
                value={form.isActive ? 'ACTIVE' : 'PASSIVE'}
                onChange={(v) => setForm({ ...form, isActive: v === 'ACTIVE' })}
              >
                <option value="ACTIVE">Aktif</option>
                <option value="PASSIVE">Pasif</option>
              </FloatingOutlineSelect>
              <div className="lg:col-span-2">
                <FloatingOutlineText
                  id="teacher-title"
                  label="Nitelik / unvan"
                  value={form.title}
                  onChange={(v) => setForm({ ...form, title: v })}
                />
              </div>
              <div className="lg:col-span-2">
                <FloatingOutlineTextarea
                  id="teacher-address"
                  label="Adres"
                  value={form.address}
                  onChange={(v) => setForm({ ...form, address: v })}
                  rows={5}
                />
              </div>
            </div>
          </OutlineFormCard>

          <OutlineFormCard title="Hesap erişimi">
            <p className="mb-4 text-sm text-light-secondary-text dark:text-zinc-400">
              Öğretmenin panele girişi için kullanılacak e-posta ve şifre.
            </p>
            <div className="grid min-w-0 grid-cols-1 gap-x-6 gap-y-4 lg:grid-cols-2">
              <FloatingOutlineText
                id="teacher-email"
                label="E-posta"
                value={form.email}
                onChange={(v) => setForm({ ...form, email: v })}
                type="email"
                required
                autoComplete="email"
              />
              <FloatingOutlineText
                id="teacher-password"
                label="Şifre"
                value={form.password}
                onChange={(v) => setForm({ ...form, password: v })}
                type="password"
                required
                minLength={6}
                autoComplete="new-password"
              />
            </div>
          </OutlineFormCard>

          <div className="flex flex-col items-stretch justify-end gap-3 pt-2 sm:flex-row sm:items-center">
            <button
              type="button"
              onClick={() => router.push('/school/teachers')}
              className="inline-flex h-9 cursor-pointer items-center justify-center rounded-full border border-gray-300 px-5 text-sm font-bold leading-6 text-gray-700 transition-colors hover:bg-gray-50 focus:outline-none dark:border-zinc-600 dark:text-zinc-200 dark:hover:bg-zinc-800"
            >
              İptal
            </button>
            <button
              type="submit"
              disabled={saving}
              className="inline-flex h-9 cursor-pointer items-center justify-center rounded-full bg-primary px-5 text-sm font-bold leading-6 text-white transition-colors hover:bg-primary-dark focus:outline-none disabled:pointer-events-none disabled:opacity-50"
            >
              {saving ? 'Kaydediliyor…' : 'Öğretmeni kaydet'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
