'use client';

import { type FormEvent, useEffect, useState } from 'react';
import { format } from 'date-fns';
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';
import { PARENTS_FAMILY_STATUS_OPTIONS } from '../../_lib/student-form-options';

type ClassroomOpt = { id: string; name: string; branchName?: string };
type AcademicTermOpt = { id: string; name: string; isActive: boolean };
type AcademicYearOpt = { id: string; name: string; isActive: boolean; terms: AcademicTermOpt[] };

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 NewStudentPage() {
  const router = useRouter();
  const { toast } = useToast();
  const [classrooms, setClassrooms] = useState<ClassroomOpt[]>([]);
  const [academicYears, setAcademicYears] = useState<AcademicYearOpt[]>([]);
  const [saving, setSaving] = useState(false);
  const [photoPreview, setPhotoPreview] = useState('');
  const [consent, setConsent] = useState(false);
  const [form, setForm] = useState({
    firstName: '',
    lastName: '',
    birthDate: '',
    gender: '',
    classroomId: '',
    bloodType: '',
    allergies: '',
    medicalNotes: '',
    address: '',
    parentsFamilyStatus: '',
    photoUrl: '',
    enrolledAt: format(new Date(), 'yyyy-MM-dd'),
    isActive: true,
    academicYearId: '',
    academicTermId: '',
  });

  useEffect(() => {
    (async () => {
      const [classRes, yearRes] = await Promise.all([
        apiFetchJson<ClassroomOpt[]>('/v1/admin/classrooms?limit=200'),
        apiFetchJson<AcademicYearOpt[]>('/v1/admin/academic-years'),
      ]);

      if (!classRes.error && classRes.data) {
        const raw = Array.isArray(classRes.data) ? classRes.data : [];
        setClassrooms(
          raw.map((c: ClassroomOpt & { branchName?: string }) => ({
            id: c.id,
            name: c.name,
            branchName: c.branchName,
          })),
        );
      }

      if (!yearRes.error && yearRes.data) {
        setAcademicYears(yearRes.data);
        // Aktif yılı ve aktif dönemi otomatik seç
        const activeYear = yearRes.data.find((y) => y.isActive);
        if (activeYear) {
          const activeTerm = activeYear.terms.find((t) => t.isActive);
          setForm((prev) => ({
            ...prev,
            academicYearId: activeYear.id,
            academicTermId: activeTerm?.id ?? '',
          }));
        }
      }
    })();
  }, []);

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


  async function submit(e: FormEvent) {
    e.preventDefault();
    if (!consent) {
      toast({
        title: 'Onay gerekli',
        description: 'Kayıt için kişisel veri işleme onayını işaretleyin.',
        variant: 'destructive',
      });
      return;
    }

    setSaving(true);
    const res = await apiFetchJson<{ id: string }>('/v1/admin/students', {
      method: 'POST',
      body: JSON.stringify({
        firstName: form.firstName,
        lastName: form.lastName,
        birthDate: form.birthDate || undefined,
        gender: form.gender || undefined,
        classroomId: form.classroomId || undefined,
        bloodType: form.bloodType || undefined,
        allergies: form.allergies || undefined,
        medicalNotes: form.medicalNotes || undefined,
        address: form.address || undefined,
        parentsFamilyStatus: form.parentsFamilyStatus || undefined,
        photoUrl: form.photoUrl || undefined,
        enrolledAt: form.enrolledAt || undefined,
        isActive: form.isActive,
      }),
    });
    if (res.error) {
      setSaving(false);
      toast({ title: 'Kayıt başarısız', description: res.error, variant: 'destructive' });
      return;
    }
    const id = (res.data as { id?: string })?.id;

    // Dönem seçildiyse enrollment oluştur
    if (id && form.academicTermId && form.classroomId) {
      await apiFetchJson(`/v1/admin/academic-terms/${form.academicTermId}/enrollments`, {
        method: 'POST',
        body: JSON.stringify({ studentId: id, classroomId: form.classroomId }),
      });
    }

    setSaving(false);
    toast({ title: 'Öğrenci kaydedildi' });
    router.push(id ? `/school/students/${id}` : '/school/students');
  }

  return (
    <div className="space-y-6 font-urbanist">
      <PageHeader
        eyebrow="Öğrenci"
        title="Yeni öğrenci"
        description="Öğrenci bilgilerini kaydedin."
        backHref="/school/students"
      />

      <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/students"
                  className="inline-flex items-center gap-1.5 text-sm text-gray-500 dark:text-gray-400"
                >
                  Öğrenciler
                  <BreadcrumbChevron />
                </Link>
              </li>
              <li className="text-sm text-gray-800 dark:text-white/90">Yeni öğrenci</li>
            </ol>
          </nav>
        </div>

        <form onSubmit={submit} className="space-y-4">
          <OutlineFormCard title="Öğrenci bilgileri">
            <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="Öğrenci 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="fn"
                  label="Ad"
                  value={form.firstName}
                  onChange={(v) => setForm({ ...form, firstName: v })}
                  required
                  autoComplete="given-name"
                />
                <FloatingOutlineText
                  id="ln"
                  label="Soyad"
                  value={form.lastName}
                  onChange={(v) => setForm({ ...form, lastName: v })}
                  required
                  autoComplete="family-name"
                />
                <FloatingOutlineDate
                  id="bd"
                  label="Doğum tarihi"
                  value={form.birthDate}
                  onChange={(v) => setForm({ ...form, birthDate: v })}
                />
                <FloatingOutlineSelect
                  id="g"
                  label="Cinsiyet"
                  value={form.gender}
                  onChange={(v) => setForm({ ...form, gender: v })}
                >
                  <option value="" className="text-gray-700 dark:bg-zinc-900 dark:text-gray-400">
                    Seçin
                  </option>
                  <option value="MALE">Erkek</option>
                  <option value="FEMALE">Kız</option>
                </FloatingOutlineSelect>
              </div>
            </div>
          </OutlineFormCard>

          <OutlineFormCard title="Okul ve kayıt">
            <div className="grid min-w-0 grid-cols-1 gap-x-6 gap-y-4 lg:grid-cols-2">
              <FloatingOutlineSelect
                id="cl"
                label="Sınıf"
                value={form.classroomId}
                onChange={(v) => setForm({ ...form, classroomId: v })}
              >
                <option value="">Atama yok</option>
                {classrooms.map((c) => (
                  <option key={c.id} value={c.id}>
                    {c.name}
                    {c.branchName ? ` · ${c.branchName}` : ''}
                  </option>
                ))}
              </FloatingOutlineSelect>
              <FloatingOutlineSelect
                id="ay"
                label="Eğitim yılı"
                value={form.academicYearId}
                onChange={(v) => {
                  setForm((prev) => ({ ...prev, academicYearId: v, academicTermId: '' }));
                }}
              >
                <option value="">Seçin (opsiyonel)</option>
                {academicYears.map((y) => (
                  <option key={y.id} value={y.id}>
                    {y.name}
                    {y.isActive ? ' · Aktif' : ''}
                  </option>
                ))}
              </FloatingOutlineSelect>
              <FloatingOutlineSelect
                id="at"
                label="Dönem"
                value={form.academicTermId}
                onChange={(v) => setForm((prev) => ({ ...prev, academicTermId: v }))}
              >
                <option value="">Seçin (opsiyonel)</option>
                {(academicYears.find((y) => y.id === form.academicYearId)?.terms ?? []).map((t) => (
                  <option key={t.id} value={t.id}>
                    {t.name}
                    {t.isActive ? ' · Aktif' : ''}
                  </option>
                ))}
              </FloatingOutlineSelect>
              <FloatingOutlineDate
                id="enr"
                label="Kayıt tarihi"
                value={form.enrolledAt}
                onChange={(v) => setForm({ ...form, enrolledAt: v })}
                required
              />
              <FloatingOutlineSelect
                id="st"
                label="Öğrenci durumu"
                value={form.isActive ? 'ACTIVE' : 'PASSIVE'}
                onChange={(v) => setForm({ ...form, isActive: v === 'ACTIVE' })}
              >
                <option value="ACTIVE">Aktif</option>
                <option value="PASSIVE">Pasif</option>
              </FloatingOutlineSelect>
              <FloatingOutlineSelect
                id="fam"
                label="Anne / baba durumu"
                value={form.parentsFamilyStatus}
                onChange={(v) => setForm({ ...form, parentsFamilyStatus: v })}
              >
                <option value="">Seçin</option>
                {PARENTS_FAMILY_STATUS_OPTIONS.map((o) => (
                  <option key={o.value} value={o.value}>
                    {o.label}
                  </option>
                ))}
              </FloatingOutlineSelect>
            </div>
          </OutlineFormCard>

          <OutlineFormCard title="Adres ve sağlık">
            <div className="space-y-4">
              <FloatingOutlineTextarea
                id="addr"
                label="Öğrenci adresi"
                value={form.address}
                onChange={(v) => setForm({ ...form, address: v })}
                rows={5}
              />
              <div className="grid grid-cols-1 gap-x-6 gap-y-4 lg:grid-cols-2">
                <FloatingOutlineText
                  id="bt"
                  label="Kan grubu"
                  value={form.bloodType}
                  onChange={(v) => setForm({ ...form, bloodType: v })}
                />
                <div className="lg:col-span-2">
                  <FloatingOutlineTextarea
                    id="al"
                    label="Alerjiler"
                    value={form.allergies}
                    onChange={(v) => setForm({ ...form, allergies: v })}
                    rows={4}
                  />
                </div>
                <div className="lg:col-span-2">
                  <FloatingOutlineTextarea
                    id="mn"
                    label="Tıbbi notlar"
                    value={form.medicalNotes}
                    onChange={(v) => setForm({ ...form, medicalNotes: v })}
                    rows={4}
                  />
                </div>
              </div>
            </div>
          </OutlineFormCard>


          <OutlineFormCard title="Kaydı tamamla">
            <p className="mb-4 text-sm text-light-secondary-text dark:text-zinc-400">
              Öğrenci kaydı oluşturulduğunda bilgiler okul yönetim sisteminizde saklanır. Veli hesapları ayrıca öğrenci detayından
              bağlanabilir.
            </p>
            <label htmlFor="consent" className="flex cursor-pointer items-start gap-3">
              <div className="relative mt-0.5 h-5 w-5 shrink-0">
                <input
                  id="consent"
                  type="checkbox"
                  checked={consent}
                  onChange={(e) => setConsent(e.target.checked)}
                  className="h-5 w-5 cursor-pointer appearance-none rounded-md border border-gray-300 checked:border-transparent checked:bg-[#0d4a42] focus:outline-none focus:ring-2 focus:ring-[#0d4a42]/30 disabled:opacity-60 dark:border-zinc-600"
                />
                {consent ? (
                  <svg
                    className="pointer-events-none absolute top-1/2 left-1/2 size-3.5 -translate-x-1/2 -translate-y-1/2"
                    xmlns="http://www.w3.org/2000/svg"
                    width={14}
                    height={14}
                    viewBox="0 0 14 14"
                    fill="none"
                    aria-hidden
                  >
                    <path
                      d="M11.6666 3.5L5.24992 9.91667L2.33325 7"
                      stroke="white"
                      strokeWidth="1.94437"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>
                ) : null}
              </div>
              <span className="text-sm font-medium text-light-primary-text dark:text-zinc-300">
                Kişisel verilerin kayıt amacıyla işlenmesini ve okul tarafından saklanmasını onaylıyorum.
              </span>
            </label>
          </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/students')}
              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…' : 'Öğrenciyi kaydet'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
