'use client';

import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useForm, useFieldArray, Control, UseFormRegister, UseFormWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import {
  Video,
  BookOpen,
  HelpCircle,
  FileText,
  Briefcase,
  FileCheck,
  Plus,
  Trash2,
  Check,
  ArrowLeft,
  Sparkles,
  AlertCircle,
  CheckCircle2,
  Layers,
  Play,
  Clock,
  FileCode,
  Edit2,
  CheckCircle,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Modal } from '@/components/ui/modal';
import {
  orientationVideoSchema,
  trainingModuleSchema,
  internshipProgramSchema,
  digitalAgreementSchema,
  OrientationVideoFormValues,
  TrainingModuleFormValues,
  InternshipProgramFormValues,
  DigitalAgreementFormValues,
  BatchMcqFormValues,
  batchMcqSchema,
} from '@/schemas/lms-creation.schema';
import {
  useCreateLmsContent,
  useUpdateLmsContent,
  useDigitalAgreements,
  useInternshipPrograms,
  useOrientationVideos,
  useQuestionTopics,
  useTrainingModules,
} from '@/services/lms/queries';
import { VideoPreviewModal } from '@/components/ui/VideoPreviewModal';

type ActiveStage =
  | 'ORIENTATION'
  | 'TRAINING'
  | 'MCQ_ASSESSMENT'
  | 'INTERNSHIP'
  | 'AGREEMENT';

export default function AdminLmsCreationPage() {
  const router = useRouter();
  const [activeStage, setActiveStage] = useState<ActiveStage>('ORIENTATION');
  const [showForm, setShowForm] = useState<boolean>(true);

  // Modal States
  const [previewVideo, setPreviewVideo] = useState<{ url: string; title: string } | null>(null);
  const [editingAsset, setEditingAsset] = useState<{ stage: ActiveStage; data: any } | null>(null);

  return (
    <div className="max-w-7xl space-y-6 animate-in fade-in duration-200 select-none pb-12">
      {/* HEADER */}
      <div className="flex items-center justify-between border-b border-border/20 pb-4">
        <div className="flex items-center gap-3">
          <Button
            type="button"
            variant="outline"
            size="icon"
            className="h-8 w-8 rounded-lg cursor-pointer"
            onClick={() => router.back()}
          >
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-sm font-black tracking-widest text-foreground uppercase flex items-center gap-2">
              <Sparkles className="h-4 w-4 text-primary" />
              LMS Curriculum & Asset Management Center
            </h1>
            <p className="text-[11px] font-medium text-muted-foreground/70">
              Manage live Advisor LMS assets, video streaming nodes, assessment banks, and legal digital agreements.
            </p>
          </div>
        </div>
      </div>

      {/* STAGE SELECTOR TABS */}
      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-2 bg-surface p-1.5 rounded-xl border border-border/40 shadow-xs">
        {[
          { id: 'ORIENTATION', label: '1. Orientation', icon: Video },
          { id: 'TRAINING', label: '2. Modules', icon: BookOpen },
          { id: 'MCQ_ASSESSMENT', label: '3. MCQ Bank', icon: HelpCircle },
          { id: 'INTERNSHIP', label: '5. Internship', icon: Briefcase },
          { id: 'AGREEMENT', label: '6. Agreement', icon: FileCheck },
        ].map((tab) => {
          const Icon = tab.icon;
          const isActive = activeStage === tab.id;
          return (
            <button
              key={tab.id}
              type="button"
              onClick={() => setActiveStage(tab.id as ActiveStage)}
              className={`flex items-center justify-center gap-1.5 py-2 px-3 rounded-lg text-[11px] font-bold transition-all cursor-pointer ${
                isActive
                  ? 'bg-primary text-primary-foreground shadow-sm'
                  : 'text-muted-foreground hover:bg-muted/40 hover:text-foreground'
              }`}
            >
              <Icon className="h-3.5 w-3.5" />
              <span className="truncate">{tab.label}</span>
            </button>
          );
        })}
      </div>

      {/* MAIN SPLIT CONTENT GRID */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
        {/* LEFT COLUMN: CREATION FORM */}
        {showForm && (
          <div className="lg:col-span-6 space-y-4">
            <div className="bg-surface border border-border/40 rounded-xl p-4 shadow-sm">
              <span className="text-[10px] font-black tracking-widest text-primary uppercase block mb-3">
                Asset Provisioning Engine
              </span>
              {activeStage === 'ORIENTATION' && <OrientationVideoForm />}
              {activeStage === 'TRAINING' && <TrainingModuleForm />}
              {activeStage === 'MCQ_ASSESSMENT' && <McqQuestionForm />}
              {activeStage === 'INTERNSHIP' && <InternshipProgramForm />}
              {activeStage === 'AGREEMENT' && <DigitalAgreementForm />}
            </div>
          </div>
        )}

        {/* RIGHT COLUMN: LIVE CREATED ASSETS DISPLAY */}
        <div className={`${showForm ? 'lg:col-span-6' : 'lg:col-span-12'} space-y-4`}>
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Layers className="h-4 w-4 text-primary" />
              <h2 className="text-xs font-black uppercase tracking-wider text-foreground">
                Live Published Assets ({activeStage.replace('_', ' ')})
              </h2>
            </div>
          </div>

          {activeStage === 'ORIENTATION' && (
            <OrientationVideosList
              onPreviewVideo={(url, title) => setPreviewVideo({ url, title })}
              onEditAsset={(item) => setEditingAsset({ stage: 'ORIENTATION', data: item })}
            />
          )}
          {activeStage === 'TRAINING' && (
            <TrainingModulesList
              onPreviewVideo={(url, title) => setPreviewVideo({ url, title })}
              onEditAsset={(item) => setEditingAsset({ stage: 'TRAINING', data: item })}
            />
          )}
          {activeStage === 'INTERNSHIP' && (
            <InternshipProgramsList onEditAsset={(item) => setEditingAsset({ stage: 'INTERNSHIP', data: item })} />
          )}
          {activeStage === 'AGREEMENT' && (
            <DigitalAgreementsList onEditAsset={(item) => setEditingAsset({ stage: 'AGREEMENT', data: item })} />
          )}
        </div>
      </div>

      {/* POPUP VIDEO PLAYER MODAL */}
      {previewVideo && (
        <VideoPreviewModal
          videoUrl={previewVideo.url}
          title={previewVideo.title}
          onClose={() => setPreviewVideo(null)}
        />
      )}

      {/* POPUP EDIT MODAL */}
      {editingAsset && (
        <Modal
          onClose={() => setEditingAsset(null)}
          icon={Edit2}
          iconClassName="text-primary"
          title={`Edit Asset: ${editingAsset.data.title}`}
        >
          <div className="p-4">
            {editingAsset.stage === 'ORIENTATION' && (
              <OrientationVideoForm initialData={editingAsset.data} onSuccess={() => setEditingAsset(null)} />
            )}
            {editingAsset.stage === 'TRAINING' && (
              <TrainingModuleForm initialData={editingAsset.data} onSuccess={() => setEditingAsset(null)} />
            )}
            {editingAsset.stage === 'INTERNSHIP' && (
              <InternshipProgramForm initialData={editingAsset.data} onSuccess={() => setEditingAsset(null)} />
            )}
            {editingAsset.stage === 'AGREEMENT' && (
              <DigitalAgreementForm initialData={editingAsset.data} onSuccess={() => setEditingAsset(null)} />
            )}
          </div>
        </Modal>
      )}
    </div>
  );
}

/* ============================================================================
   INVENTORY LISTS WITH EDIT TRIGGER
============================================================================ */
function OrientationVideosList({
  onPreviewVideo,
  onEditAsset,
}: {
  onPreviewVideo: (url: string, title: string) => void;
  onEditAsset: (item: any) => void;
}) {
  const { data: videos = [], isLoading } = useOrientationVideos();

  if (isLoading) return <LoadingCardSkeleton />;
  if (videos.length === 0) return <EmptyStateCard stage="Orientation Videos" />;

  return (
    <div className="space-y-3">
      {videos.map((item: any, idx: number) => (
        <div
          key={item.id}
          className="p-4 rounded-xl border border-border/40 bg-surface space-y-3 shadow-xs hover:border-border/80 transition-all"
        >
          <div className="flex items-start justify-between gap-3">
            <div className="flex items-start gap-3">
              <span className="h-7 w-7 rounded-lg bg-primary/10 text-primary text-xs font-black flex items-center justify-center font-mono shrink-0">
                #{item.sequence ?? idx + 1}
              </span>
              <div>
                <h3 className="text-xs font-bold text-foreground leading-tight">{item.title}</h3>
                <p className="text-[11px] text-muted-foreground/80 line-clamp-2 mt-0.5">
                  {item.description || 'No detailed description provided.'}
                </p>
              </div>
            </div>

            <div className="flex items-center gap-2 shrink-0">
              <span
                className={`text-[10px] font-bold px-2 py-0.5 rounded-full border ${
                  item.orientationVideo?.isMandatory
                    ? 'bg-amber-500/10 text-amber-500 border-amber-500/20'
                    : 'bg-muted/40 text-muted-foreground border-border/30'
                }`}
              >
                {item.orientationVideo?.isMandatory ? 'Mandatory' : 'Optional'}
              </span>

              <button
                type="button"
                onClick={() => onEditAsset(item)}
                className="p-1.5 text-muted-foreground hover:text-primary hover:bg-primary/10 rounded-lg transition-colors cursor-pointer"
                title="Edit asset"
              >
                <Edit2 className="h-3.5 w-3.5" />
              </button>
            </div>
          </div>

          <div className="flex items-center justify-between text-[10px] font-mono text-muted-foreground pt-2 border-t border-border/10">
            <div className="flex items-center gap-3">
              <span className="flex items-center gap-1">
                <Clock className="h-3 w-3 text-primary" /> {Math.round(item.durationSec / 60)} mins ({item.durationSec}s)
              </span>
              <button
                type="button"
                onClick={() => onPreviewVideo(item.url, item.title)}
                className="flex items-center gap-1.5 text-primary hover:underline font-bold cursor-pointer"
              >
                <Play className="h-3.5 w-3.5 fill-primary/20 text-primary" /> Preview Stream
              </button>
            </div>
            <span>ID: {item.id.slice(0, 8)}...</span>
          </div>
        </div>
      ))}
    </div>
  );
}

function TrainingModulesList({
  onPreviewVideo,
  onEditAsset,
}: {
  onPreviewVideo: (url: string, title: string) => void;
  onEditAsset: (item: any) => void;
}) {
  const { data: modules = [], isLoading } = useTrainingModules();

  if (isLoading) return <LoadingCardSkeleton />;
  if (modules.length === 0) return <EmptyStateCard stage="Training Modules" />;

  return (
    <div className="space-y-3">
      {modules.map((m: any, idx: number) => (
        <div
          key={m.id}
          className="p-4 rounded-xl border border-border/40 bg-surface space-y-3 shadow-xs hover:border-border/80 transition-all"
        >
          <div className="flex items-start justify-between gap-2">
            <div className="flex items-start gap-3">
              <span className="h-7 w-7 rounded-lg bg-primary/10 text-primary text-xs font-black flex items-center justify-center font-mono shrink-0">
                M{m.sequence ?? idx + 1}
              </span>
              <div>
                <h3 className="text-xs font-bold text-foreground leading-tight">{m.title}</h3>
                <p className="text-[11px] text-muted-foreground/80 line-clamp-2 mt-0.5">
                  {m.description || 'Syllabus notes omitted.'}
                </p>
              </div>
            </div>

            <button
              type="button"
              onClick={() => onEditAsset(m)}
              className="p-1.5 text-muted-foreground hover:text-primary hover:bg-primary/10 rounded-lg transition-colors cursor-pointer shrink-0"
              title="Edit module"
            >
              <Edit2 className="h-3.5 w-3.5" />
            </button>
          </div>

          <div className="flex items-center gap-4 text-[10px] font-mono text-muted-foreground pt-2 border-t border-border/10">
            {m.pdfUrl && (
              <a href={m.pdfUrl} target="_blank" rel="noreferrer" className="flex items-center gap-1 text-primary hover:underline">
                <FileCode className="h-3 w-3" /> Handbook PDF
              </a>
            )}
            {m.videoUrl || m.videoAsset ? (
              <button
                type="button"
                onClick={() => onPreviewVideo(m.videoUrl || m.videoAsset?.url, m.title)}
                className="flex items-center gap-1 text-emerald-500 font-bold hover:underline cursor-pointer"
              >
                <Play className="h-3 w-3 fill-emerald-500/20 text-emerald-500" /> Preview Video
              </button>
            ) : null}
            <span className="ml-auto">Duration: {m.durationSec}s</span>
          </div>
        </div>
      ))}
    </div>
  );
}

function InternshipProgramsList({ onEditAsset }: { onEditAsset?: (item: any) => void }) {
  const { data: programs = [], isLoading } = useInternshipPrograms();

  if (isLoading) return <LoadingCardSkeleton />;
  if (programs.length === 0) return <EmptyStateCard stage="Internship Programs" />;

  return (
    <div className="space-y-3">
      {programs.map((p: any) => (
        <div key={p.id} className="p-4 rounded-xl border border-border/40 bg-surface space-y-2 shadow-xs">
          <div className="flex items-center justify-between">
            <h3 className="text-xs font-bold text-foreground">{p.title}</h3>
            <div className="flex items-center gap-2">
              <span className="text-[10px] font-mono bg-emerald-500/10 text-emerald-500 px-2 py-0.5 rounded-md font-bold">
                {p.defaultDurationDays} Days Scope
              </span>
              {onEditAsset && (
                <button
                  type="button"
                  onClick={() => onEditAsset(p)}
                  className="p-1 text-muted-foreground hover:text-primary rounded-md transition-colors"
                >
                  <Edit2 className="h-3.5 w-3.5" />
                </button>
              )}
            </div>
          </div>
          <p className="text-[11px] text-muted-foreground/80">{p.description}</p>
        </div>
      ))}
    </div>
  );
}

function DigitalAgreementsList({ onEditAsset }: { onEditAsset?: (item: any) => void }) {
  const { data: agreements = [], isLoading } = useDigitalAgreements();

  if (isLoading) return <LoadingCardSkeleton />;
  if (agreements.length === 0) return <EmptyStateCard stage="Digital Legal Agreements" />;

  return (
    <div className="space-y-3">
      {agreements.map((a: any) => (
        <div key={a.id} className="p-4 rounded-xl border border-border/40 bg-surface space-y-2 shadow-xs">
          <div className="flex items-center justify-between">
            <span className="text-[10px] font-mono bg-primary/10 text-primary px-2 py-0.5 rounded-md font-bold">
              {a.version}
            </span>
            <div className="flex items-center gap-2">
              <span className="text-[10px] font-bold text-emerald-500 flex items-center gap-1">
                <CheckCircle className="h-3 w-3" /> Active Document
              </span>
              {onEditAsset && (
                <button
                  type="button"
                  onClick={() => onEditAsset(a)}
                  className="p-1 text-muted-foreground hover:text-primary rounded-md transition-colors"
                >
                  <Edit2 className="h-3.5 w-3.5" />
                </button>
              )}
            </div>
          </div>
          <h3 className="text-xs font-bold text-foreground">{a.title}</h3>
        </div>
      ))}
    </div>
  );
}

/* ============================================================================
   DUAL-MODE FORMS (CREATE / UPDATE)
============================================================================ */
function OrientationVideoForm({
  initialData,
  onSuccess,
}: {
  initialData?: any;
  onSuccess?: () => void;
}) {
  const createMutation = useCreateLmsContent('ORIENTATION');
  const updateMutation = useUpdateLmsContent('ORIENTATION');
  const isEditing = !!initialData;

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<OrientationVideoFormValues>({
    resolver: zodResolver(orientationVideoSchema),
    defaultValues: initialData
      ? {
          title: initialData.title,
          description: initialData.description || '',
          url: initialData.url,
          thumbnailUrl: initialData.thumbnailUrl || '',
          durationSec: initialData.durationSec,
          sequence: initialData.sequence || 0,
          isMandatory: initialData.orientationVideo?.isMandatory ?? true,
        }
      : { isMandatory: true, sequence: 0, durationSec: 120 },
  });

  const onSubmit = async (data: OrientationVideoFormValues) => {
    if (isEditing) {
      await updateMutation.mutateAsync({ id: initialData.id, payload: data });
    } else {
      await createMutation.mutateAsync(data);
      reset();
    }
    if (onSuccess) onSuccess();
  };

  const isPending = createMutation.isPending || updateMutation.isPending;

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
      <div className="border border-border/40 rounded-xl bg-surface p-5 space-y-4 shadow-sm">
        <div className="flex items-center gap-2 border-b border-border/10 pb-2">
          <Video className="h-4 w-4 text-primary" />
          <h2 className="text-xs font-bold uppercase tracking-wider text-foreground">
            {isEditing ? 'Edit Orientation Video' : 'Stage 1: Orientation Video Asset'}
          </h2>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          <div className="md:col-span-2">
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Video Title *
            </label>
            <input
              type="text"
              {...register('title')}
              placeholder="e.g. Welcome to Smart Skills India Advisor Portal"
              className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
            {errors.title && <span className="text-[10px] text-destructive block mt-0.5">{errors.title.message}</span>}
          </div>

          <div className="md:col-span-2">
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Description / Learning Objectives
            </label>
            <textarea
              rows={2}
              {...register('description')}
              placeholder="Overview of expectations, roles, and ecosystem architecture..."
              className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Media Stream URL (MP4 / HLS / YouTube) *
            </label>
            <input
              type="text"
              {...register('url')}
              placeholder="https://cdn.smartskills.in/videos/orientation-01.mp4"
              className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
            {errors.url && <span className="text-[10px] text-destructive block mt-0.5">{errors.url.message}</span>}
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Thumbnail Cover Image URL
            </label>
            <input
              type="text"
              {...register('thumbnailUrl')}
              placeholder="https://cdn.smartskills.in/thumbs/orientation-01.jpg"
              className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Duration (Seconds) *
            </label>
            <input
              type="number"
              {...register('durationSec')}
              className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Playback Sequence Order
            </label>
            <input
              type="number"
              {...register('sequence')}
              className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
          </div>

          <div className="md:col-span-2 pt-2">
            <label className="flex items-center gap-2 cursor-pointer text-xs font-bold text-foreground">
              <input
                type="checkbox"
                {...register('isMandatory')}
                className="h-4 w-4 rounded border-border/40 text-primary focus:ring-primary"
              />
              Mandatory Video (advisor cannot skip or unlock next stage without completing)
            </label>
          </div>
        </div>
      </div>

      <SubmitButton isPending={isPending} label={isEditing ? 'Save Changes' : 'Add Orientation Video'} />
    </form>
  );
}

function TrainingModuleForm({
  initialData,
  onSuccess,
}: {
  initialData?: any;
  onSuccess?: () => void;
}) {
  const createMutation = useCreateLmsContent('TRAINING');
  const updateMutation = useUpdateLmsContent('TRAINING');
  const isEditing = !!initialData;

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<TrainingModuleFormValues>({
    resolver: zodResolver(trainingModuleSchema),
    defaultValues: initialData
      ? {
          title: initialData.title,
          description: initialData.description || '',
          videoUrl: initialData.videoUrl || initialData.videoAsset?.url || '',
          pdfUrl: initialData.pdfUrl || '',
          durationSec: initialData.durationSec || 300,
          sequence: initialData.sequence || 0,
          isMandatory: initialData.isMandatory ?? true,
        }
      : { isMandatory: true, sequence: 0, durationSec: 300 },
  });

  const onSubmit = async (data: TrainingModuleFormValues) => {
    if (isEditing) {
      await updateMutation.mutateAsync({ id: initialData.id, payload: data });
    } else {
      await createMutation.mutateAsync(data);
      reset();
    }
    if (onSuccess) onSuccess();
  };

  const isPending = createMutation.isPending || updateMutation.isPending;

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
      <div className="border border-border/40 rounded-xl bg-surface p-5 space-y-4 shadow-sm">
        <div className="flex items-center gap-2 border-b border-border/10 pb-2">
          <BookOpen className="h-4 w-4 text-primary" />
          <h2 className="text-xs font-bold uppercase tracking-wider text-foreground">
            {isEditing ? 'Edit Training Module' : 'Stage 2: Training Module & Material'}
          </h2>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          <div className="md:col-span-2">
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Module Title *
            </label>
            <input
              type="text"
              {...register('title')}
              placeholder="e.g. Module 1: Student Counseling & Program Guidance Skills"
              className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
            {errors.title && <span className="text-[10px] text-destructive block mt-0.5">{errors.title.message}</span>}
          </div>

          <div className="md:col-span-2">
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Module Summary & Curriculum Syllabus
            </label>
            <textarea
              rows={2}
              {...register('description')}
              placeholder="Key concepts covered in this training chapter..."
              className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Embedded Video Asset URL
            </label>
            <input
              type="text"
              {...register('videoUrl')}
              placeholder="https://cdn.smartskills.in/training/module-01.mp4"
              className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Study Material PDF Document URL
            </label>
            <input
              type="text"
              {...register('pdfUrl')}
              placeholder="https://cdn.smartskills.in/docs/module-01-handbook.pdf"
              className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Estimated Completion Duration (Seconds)
            </label>
            <input
              type="number"
              {...register('durationSec')}
              className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Sequence Order
            </label>
            <input
              type="number"
              {...register('sequence')}
              className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
          </div>
        </div>
      </div>

      <SubmitButton isPending={isPending} label={isEditing ? 'Save Module Changes' : 'Create Training Module'} />
    </form>
  );
}

function McqQuestionForm() {
  const mutation = useCreateLmsContent('MCQ_ASSESSMENT');
  const { data: topics = [] } = useQuestionTopics();

  const {
    register,
    control,
    handleSubmit,
    watch,
    setValue,
    reset,
    formState: { errors },
  } = useForm<BatchMcqFormValues>({
    resolver: zodResolver(batchMcqSchema),
    defaultValues: {
      topicId: '',
      questions: [
        {
          questionText: '',
          type: 'SINGLE_CORRECT',
          difficulty: 'MEDIUM',
          explanation: '',
          options: [
            { optionText: '', isCorrect: true },
            { optionText: '', isCorrect: false },
            { optionText: '', isCorrect: false },
            { optionText: '', isCorrect: false },
          ],
        },
      ],
    },
  });

  const { fields: questionFields, append: appendQuestion, remove: removeQuestion } = useFieldArray({
    control,
    name: 'questions',
  });

  const onSubmit = async (data: BatchMcqFormValues) => {
    await mutation.mutateAsync(data);
    reset();
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
      <div className="border border-border/40 rounded-xl bg-surface p-5 space-y-4 shadow-sm">
        <div className="flex items-center justify-between border-b border-border/10 pb-3">
          <div className="flex items-center gap-2">
            <HelpCircle className="h-4 w-4 text-primary" />
            <h2 className="text-xs font-bold uppercase tracking-wider text-foreground">
              Stage 3: Bulk MCQ Question Bank Provisioning
            </h2>
          </div>
          <span className="text-[10px] font-mono font-bold text-muted-foreground bg-muted/40 px-2.5 py-1 rounded-md">
            Questions in Batch: {questionFields.length}
          </span>
        </div>

        <div>
          <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
            Topic Category (Applied to all questions in this batch) *
          </label>
          <select
            {...register('topicId')}
            className="w-full md:w-1/2 text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
          >
            <option value="">-- Choose Question Topic Category --</option>
            {topics.map((t: { id: string; name: string }) => (
              <option key={t.id} value={t.id}>
                {t.name}
              </option>
            ))}
          </select>
          {errors.topicId && (
            <span className="text-[10px] text-destructive block mt-0.5">{errors.topicId.message}</span>
          )}
        </div>
      </div>

      <div className="space-y-4">
        {questionFields.map((qField, qIdx) => (
          <QuestionCard
            key={qField.id}
            qIdx={qIdx}
            control={control}
            register={register}
            watch={watch}
            setValue={setValue}
            onRemove={() => removeQuestion(qIdx)}
            canRemove={questionFields.length > 1}
            errors={errors.questions?.[qIdx]}
          />
        ))}
      </div>

      <div className="flex items-center justify-between border-t border-border/10 pt-4">
        <Button
          type="button"
          variant="outline"
          onClick={() =>
            appendQuestion({
              questionText: '',
              type: 'SINGLE_CORRECT',
              difficulty: 'MEDIUM',
              explanation: '',
              options: [
                { optionText: '', isCorrect: true },
                { optionText: '', isCorrect: false },
                { optionText: '', isCorrect: false },
                { optionText: '', isCorrect: false },
              ],
            })
          }
          className="h-9 px-4 text-xs font-bold gap-1.5 border-dashed cursor-pointer"
        >
          <Plus className="h-4 w-4" /> Add Another Question to Batch
        </Button>

        <Button
          type="submit"
          disabled={mutation.isPending}
          className="h-9 px-6 rounded-lg text-xs font-bold shadow-sm bg-primary text-primary-foreground hover:bg-primary/90 cursor-pointer"
        >
          <span>{mutation.isPending ? 'Saving Batch...' : `Submit Batch (${questionFields.length} Questions)`}</span>
        </Button>
      </div>
    </form>
  );
}

interface QuestionCardProps {
  qIdx: number;
  control: Control<BatchMcqFormValues>;
  register: UseFormRegister<BatchMcqFormValues>;
  watch: UseFormWatch<BatchMcqFormValues>;
  setValue: any;
  onRemove: () => void;
  canRemove: boolean;
  errors?: any;
}

function QuestionCard({
  qIdx,
  control,
  register,
  watch,
  setValue,
  onRemove,
  canRemove,
  errors,
}: QuestionCardProps) {
  const { fields: optionFields, append: appendOption, remove: removeOption, replace: replaceOptions } = useFieldArray({
    control,
    name: `questions.${qIdx}.options`,
  });

  const questionType = watch(`questions.${qIdx}.type`);
  const currentOptions = watch(`questions.${qIdx}.options`);

  useEffect(() => {
    if (questionType === 'TRUE_FALSE') {
      replaceOptions([
        { optionText: 'True', isCorrect: true },
        { optionText: 'False', isCorrect: false },
      ]);
    }
  }, [questionType, replaceOptions]);

  const handleOptionCorrectChange = (optIdx: number, isChecked: boolean) => {
    if (questionType === 'SINGLE_CORRECT' || questionType === 'TRUE_FALSE') {
      const updated = currentOptions.map((opt: any, idx: number) => ({
        ...opt,
        isCorrect: idx === optIdx ? isChecked : false,
      }));
      setValue(`questions.${qIdx}.options`, updated, { shouldValidate: true });
    } else {
      setValue(`questions.${qIdx}.options.${optIdx}.isCorrect`, isChecked, { shouldValidate: true });
    }
  };

  const correctCount = currentOptions?.filter((o: any) => o.isCorrect).length || 0;

  return (
    <div className="border border-border/40 rounded-xl bg-surface p-5 space-y-4 shadow-sm relative">
      <div className="flex items-center justify-between border-b border-border/10 pb-2.5">
        <div className="flex items-center gap-2">
          <span className="h-6 w-6 rounded-md bg-primary/10 text-primary text-[11px] font-black flex items-center justify-center font-mono">
            #{qIdx + 1}
          </span>
          <span className="text-xs font-bold text-foreground">Question Configuration</span>
        </div>

        <div className="flex items-center gap-2">
          <span
            className={`text-[10px] font-bold px-2 py-0.5 rounded-full border ${
              questionType === 'MULTIPLE_CORRECT'
                ? 'bg-amber-500/10 text-amber-500 border-amber-500/20'
                : 'bg-primary/10 text-primary border-primary/20'
            }`}
          >
            {questionType === 'MULTIPLE_CORRECT'
              ? 'Multiple Correct Choices (MSQ)'
              : questionType === 'TRUE_FALSE'
              ? 'True / False'
              : 'Single Correct Choice'}
          </span>

          {canRemove && (
            <button
              type="button"
              onClick={onRemove}
              className="text-muted-foreground hover:text-destructive p-1 rounded-md transition-colors"
              title="Remove question"
            >
              <Trash2 className="h-4 w-4" />
            </button>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
        <div>
          <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
            Question Type *
          </label>
          <select
            {...register(`questions.${qIdx}.type`)}
            className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
          >
            <option value="SINGLE_CORRECT">Single Correct Choice</option>
            <option value="MULTIPLE_CORRECT">Multiple Correct Choices (MSQ)</option>
            <option value="TRUE_FALSE">True / False</option>
          </select>
        </div>

        <div>
          <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
            Difficulty Tier *
          </label>
          <select
            {...register(`questions.${qIdx}.difficulty`)}
            className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
          >
            <option value="EASY">Easy</option>
            <option value="MEDIUM">Medium</option>
            <option value="HARD">Hard</option>
          </select>
        </div>

        <div className="md:col-span-2">
          <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
            Question Statement *
          </label>
          <textarea
            rows={2}
            {...register(`questions.${qIdx}.questionText`)}
            placeholder="Enter question prompt..."
            className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
          />
          {errors?.questionText && (
            <span className="text-[10px] text-destructive block mt-0.5">{errors.questionText.message}</span>
          )}
        </div>

        <div className="md:col-span-2">
          <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
            Explanation (Optional)
          </label>
          <input
            type="text"
            {...register(`questions.${qIdx}.explanation`)}
            placeholder="Explanation for the correct answer..."
            className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
          />
        </div>
      </div>

      <div className="space-y-2.5 pt-2 border-t border-border/10">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <span className="text-[11px] font-bold uppercase tracking-wider text-foreground">Answer Options</span>
            <span className="text-[10px] font-mono text-muted-foreground">({correctCount} selected as correct)</span>
          </div>

          {questionType !== 'TRUE_FALSE' && (
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() => appendOption({ optionText: '', isCorrect: false })}
              className="h-6 text-[10px] gap-1 cursor-pointer"
            >
              <Plus className="h-3 w-3" /> Add Choice
            </Button>
          )}
        </div>

        {errors?.options && (
          <div className="flex items-center gap-1.5 p-2 bg-destructive/10 border border-destructive/20 text-destructive text-[10px] font-medium rounded-lg">
            <AlertCircle className="h-3.5 w-3.5 shrink-0" />
            <span>{errors.options.message}</span>
          </div>
        )}

        <div className="space-y-2">
          {optionFields.map((optField, optIdx) => {
            const isCorrect = currentOptions?.[optIdx]?.isCorrect || false;

            return (
              <div
                key={optField.id}
                className={`flex items-center gap-2.5 p-2 rounded-lg border transition-all ${
                  isCorrect ? 'bg-emerald-500/5 border-emerald-500/30' : 'bg-background border-border/30'
                }`}
              >
                <label className="flex items-center gap-1 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={isCorrect}
                    onChange={(e) => handleOptionCorrectChange(optIdx, e.target.checked)}
                    className="h-4 w-4 rounded border-border/40 text-emerald-500 focus:ring-emerald-500 cursor-pointer"
                  />
                  <CheckCircle2
                    className={`h-3.5 w-3.5 ${isCorrect ? 'text-emerald-500' : 'text-muted-foreground/30'}`}
                  />
                </label>

                <input
                  type="text"
                  {...register(`questions.${qIdx}.options.${optIdx}.optionText`)}
                  disabled={questionType === 'TRUE_FALSE'}
                  placeholder={`Option ${optIdx + 1} text...`}
                  className="flex-1 text-xs font-medium px-3 py-1.5 border border-border/30 rounded-md focus:outline-none focus:border-primary disabled:bg-muted/30"
                />

                {questionType !== 'TRUE_FALSE' && optionFields.length > 2 && (
                  <button
                    type="button"
                    onClick={() => removeOption(optIdx)}
                    className="text-muted-foreground hover:text-destructive p-1 rounded-md transition-colors"
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function InternshipProgramForm({
  initialData,
  onSuccess,
}: {
  initialData?: any;
  onSuccess?: () => void;
}) {
  const createMutation = useCreateLmsContent('INTERNSHIP');
  const updateMutation = useUpdateLmsContent('INTERNSHIP');
  const isEditing = !!initialData;

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<InternshipProgramFormValues>({
    resolver: zodResolver(internshipProgramSchema),
    defaultValues: initialData
      ? {
          title: initialData.title,
          description: initialData.description || '',
          defaultDurationDays: initialData.defaultDurationDays || 30,
        }
      : { defaultDurationDays: 30 },
  });

  const onSubmit = async (data: InternshipProgramFormValues) => {
    if (isEditing) {
      await updateMutation.mutateAsync({ id: initialData.id, payload: data });
    } else {
      await createMutation.mutateAsync(data);
      reset();
    }
    if (onSuccess) onSuccess();
  };

  const isPending = createMutation.isPending || updateMutation.isPending;

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
      <div className="border border-border/40 rounded-xl bg-surface p-5 space-y-4 shadow-sm">
        <div className="flex items-center gap-2 border-b border-border/10 pb-2">
          <Briefcase className="h-4 w-4 text-primary" />
          <h2 className="text-xs font-bold uppercase tracking-wider text-foreground">
            {isEditing ? 'Edit Internship Program' : 'Stage 5: Practical Field Internship Program'}
          </h2>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          <div className="md:col-span-2">
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Program Title *
            </label>
            <input
              type="text"
              {...register('title')}
              placeholder="e.g. 30-Day Practical Campus Mentorship & Student Onboarding Internship"
              className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
            {errors.title && <span className="text-[10px] text-destructive block mt-0.5">{errors.title.message}</span>}
          </div>

          <div className="md:col-span-2">
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Internship Guidelines & Daily Deliverable Scope
            </label>
            <textarea
              rows={3}
              {...register('description')}
              placeholder="Daily reporting criteria, student interaction logs, and mentor review expectations..."
              className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Standard Internship Duration (Days) *
            </label>
            <input
              type="number"
              {...register('defaultDurationDays')}
              className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
          </div>
        </div>
      </div>

      <SubmitButton isPending={isPending} label={isEditing ? 'Save Program Changes' : 'Deploy Internship Program'} />
    </form>
  );
}

function DigitalAgreementForm({
  initialData,
  onSuccess,
}: {
  initialData?: any;
  onSuccess?: () => void;
}) {
  const createMutation = useCreateLmsContent('AGREEMENT');
  const updateMutation = useUpdateLmsContent('AGREEMENT');
  const isEditing = !!initialData;

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<DigitalAgreementFormValues>({
    resolver: zodResolver(digitalAgreementSchema),
    defaultValues: initialData
      ? {
          version: initialData.version,
          title: initialData.title,
          bodyHtml: initialData.bodyHtml || '',
          termsUrl: initialData.termsUrl || '',
          privacyPolicyUrl: initialData.privacyPolicyUrl || '',
          codeOfConductUrl: initialData.codeOfConductUrl || '',
        }
      : { version: 'v1.0' },
  });

  const onSubmit = async (data: DigitalAgreementFormValues) => {
    if (isEditing) {
      await updateMutation.mutateAsync({ id: initialData.id, payload: data });
    } else {
      await createMutation.mutateAsync(data);
      reset();
    }
    if (onSuccess) onSuccess();
  };

  const isPending = createMutation.isPending || updateMutation.isPending;

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
      <div className="border border-border/40 rounded-xl bg-surface p-5 space-y-4 shadow-sm">
        <div className="flex items-center gap-2 border-b border-border/10 pb-2">
          <FileCheck className="h-4 w-4 text-primary" />
          <h2 className="text-xs font-bold uppercase tracking-wider text-foreground">
            {isEditing ? 'Edit Digital Agreement' : 'Stage 6: Advisor Digital Agreement & Terms Asset'}
          </h2>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          <div>
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Agreement Version *
            </label>
            <input
              type="text"
              {...register('version')}
              placeholder="v1.0"
              className="w-full text-xs font-mono font-bold px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
            {errors.version && <span className="text-[10px] text-destructive block mt-0.5">{errors.version.message}</span>}
          </div>

          <div className="md:col-span-2">
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Document Title *
            </label>
            <input
              type="text"
              {...register('title')}
              placeholder="e.g. Master Career Advisor Engagement Agreement & Code of Conduct"
              className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
            {errors.title && <span className="text-[10px] text-destructive block mt-0.5">{errors.title.message}</span>}
          </div>

          <div className="md:col-span-3">
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Agreement Body (HTML / Formatted Legal Terms) *
            </label>
            <textarea
              rows={5}
              {...register('bodyHtml')}
              placeholder="<p>This Agreement specifies the operational terms...</p>"
              className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
            {errors.bodyHtml && <span className="text-[10px] text-destructive block mt-0.5">{errors.bodyHtml.message}</span>}
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              External Terms Document URL
            </label>
            <input
              type="text"
              {...register('termsUrl')}
              placeholder="https://smartskills.in/terms"
              className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Privacy Policy Link
            </label>
            <input
              type="text"
              {...register('privacyPolicyUrl')}
              placeholder="https://smartskills.in/privacy"
              className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
          </div>

          <div>
            <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
              Code of Conduct Link
            </label>
            <input
              type="text"
              {...register('codeOfConductUrl')}
              placeholder="https://smartskills.in/code-of-conduct"
              className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
            />
          </div>
        </div>
      </div>

      <SubmitButton isPending={isPending} label={isEditing ? 'Save Agreement Changes' : 'Publish Digital Agreement'} />
    </form>
  );
}

/* ============================================================================
   SHARED UTILITY HELPERS
============================================================================ */
function SubmitButton({ isPending, label }: { isPending: boolean; label: string }) {
  return (
    <div className="flex justify-end">
      <Button
        type="submit"
        disabled={isPending}
        className="h-9 px-5 rounded-lg text-xs font-bold gap-1.5 shadow-sm bg-primary text-primary-foreground hover:bg-primary/90 cursor-pointer"
      >
        <Check className="h-4 w-4 stroke-[2.5]" />
        <span>{isPending ? 'Provisioning Asset...' : label}</span>
      </Button>
    </div>
  );
}

function LoadingCardSkeleton() {
  return (
    <div className="space-y-3 animate-pulse">
      {[1, 2].map((i) => (
        <div key={i} className="h-24 rounded-xl border border-border/30 bg-surface/50" />
      ))}
    </div>
  );
}

function EmptyStateCard({ stage }: { stage: string }) {
  return (
    <div className="p-8 rounded-xl border border-dashed border-border/40 bg-surface text-center space-y-2">
      <Layers className="h-6 w-6 text-muted-foreground/40 mx-auto" />
      <p className="text-xs font-bold text-muted-foreground">No {stage} provisioned yet.</p>
      <p className="text-[10px] text-muted-foreground/60">
        Use the form on the left to deploy new assets to the Career Advisor LMS pipeline.
      </p>
    </div>
  );
}