import { ChevronDown, Plus, Settings, Trash2 } from 'lucide-react';
import { useState } from 'react';
import type { ReactNode } from 'react';

import { useSafetyQuizContentEditor } from '@/business/safety-quiz/hooks';
import { Button } from '@/components/ui/button';
import { ConfirmationDialog } from '@/components/common/ConfirmationDialog';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { Input } from '@/components/ui/input';
import { NativeSelect } from '@/components/ui/native-select';
import { StatePanel } from '@/components/ui/state-panel';
import { Textarea } from '@/components/ui/textarea';
import type { SafetyQuiz } from '@/shared/types/app';

const focusOptions: readonly { value: SafetyQuiz['focus']; label: string }[] = [
  { value: 'de-escalation', label: 'De-escalation' },
  { value: 'physical-management', label: 'Physical management' },
  { value: 'safety-reminders', label: 'Safety reminders' },
];

const inputClassName = 'border-slate-700/60 bg-slate-950/70 text-slate-100 placeholder:text-slate-500';
const labelClassName = 'text-xs font-semibold uppercase tracking-wide text-slate-400';
const sectionClassName = 'rounded-xl border border-slate-700/50 bg-slate-950/30 p-4 space-y-4';
const iconButtonClassName = 'h-9 w-9 border border-slate-700/60 text-slate-300 hover:bg-slate-700/40';

export function SafetyQuizContentEditorPanel() {
  const editor = useSafetyQuizContentEditor();
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [open, setOpen] = useState(false);
  const disabled = editor.isLoading || editor.isSaving || editor.isDeleting;
  const quiz = editor.draft;

  return (
    <Collapsible
      open={open}
      onOpenChange={setOpen}
      className="rounded-2xl border border-slate-700/40 bg-slate-800/40"
    >
      <div className="flex flex-col gap-3 border-b border-slate-700/40 p-4 sm:flex-row sm:items-center sm:justify-between">
        <CollapsibleTrigger asChild>
          <button
            type="button"
            className="flex min-w-0 flex-1 items-center gap-3 rounded-xl text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-400"
            aria-label={open ? 'Collapse quiz editor' : 'Expand quiz editor'}
          >
            <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-blue-500/15 text-blue-300">
              <Settings size={18} />
            </span>
            <span className="min-w-0">
              <span className="block text-sm font-semibold text-white">Quiz Content Editor</span>
              <span className="block text-xs text-slate-400">Edit the weekly QBS quiz and key reminders.</span>
            </span>
            <ChevronDown
              size={18}
              className={`ml-auto text-slate-400 transition-transform ${open ? 'rotate-180' : ''}`}
            />
          </button>
        </CollapsibleTrigger>
        <div className="flex shrink-0 flex-wrap gap-2 sm:justify-end">
          <Button
            type="button"
            variant="ghost"
            leadingIcon={<Plus size={16} />}
            onClick={() => {
              editor.addDefaultQuiz();
              setOpen(true);
            }}
            disabled={disabled}
            className="border border-emerald-500/30 bg-emerald-500/10 text-emerald-200 hover:bg-emerald-500/20"
          >
            {quiz ? 'Replace with Default' : 'Add Quiz'}
          </Button>
          <Button
            type="button"
            variant="ghost"
            leadingIcon={<Trash2 size={16} />}
            onClick={() => {
              setDeleteOpen(true);
              setOpen(true);
            }}
            disabled={disabled || !quiz}
            className="border border-red-500/30 bg-red-500/10 text-red-200 hover:bg-red-500/20"
          >
            Delete Quiz
          </Button>
        </div>
      </div>

      <CollapsibleContent className="space-y-4 p-4">
        {editor.errorMessage && (
          <StatePanel tone="red" role="alert" size="inline">
            {editor.errorMessage}
          </StatePanel>
        )}

        {editor.validationError && (
          <StatePanel tone="red" role="alert" size="inline">
            {editor.validationError}
          </StatePanel>
        )}

        {editor.savedMessage && (
          <StatePanel tone="cyan" size="inline">
            {editor.savedMessage}
          </StatePanel>
        )}

        {!quiz ? (
          <div className="rounded-xl border border-dashed border-slate-700/70 bg-slate-950/30 px-4 py-8 text-center">
            <p className="text-sm font-semibold text-slate-100">No QBS quiz is configured.</p>
            <p className="mt-1 text-sm text-slate-400">Add a quiz to publish questions and reminders for this scope.</p>
          </div>
        ) : (
          <form
            className="space-y-4"
            onSubmit={(event) => {
              event.preventDefault();
              void editor.save();
            }}
          >
          <div className={sectionClassName}>
            <div className="grid gap-4 lg:grid-cols-2">
              <Field label="Quiz title">
                <Input
                  value={quiz.title}
                  onChange={(event) => editor.updateQuiz({ title: event.target.value })}
                  disabled={disabled}
                  className={inputClassName}
                  placeholder="QBS Safety Quiz"
                />
              </Field>
              <Field label="Focus">
                <NativeSelect
                  value={quiz.focus}
                  onChange={(event) => {
                    const focus = focusOptions.find((option) => option.value === event.target.value)?.value;
                    if (focus) {
                      editor.updateQuiz({ focus });
                    }
                  }}
                  disabled={disabled}
                  className={inputClassName}
                >
                  {focusOptions.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </NativeSelect>
              </Field>
            </div>

            <div className="grid gap-4 lg:grid-cols-2">
              <Field label="Weekly focus title">
                <Input
                  value={quiz.weeklyFocus.title}
                  onChange={(event) => editor.updateWeeklyFocus({ title: event.target.value })}
                  disabled={disabled}
                  className={inputClassName}
                  placeholder="This week's focus"
                />
              </Field>
              <Field label="Weekly focus description">
                <Textarea
                  value={quiz.weeklyFocus.description}
                  onChange={(event) => editor.updateWeeklyFocus({ description: event.target.value })}
                  disabled={disabled}
                  className={`${inputClassName} min-h-24`}
                  placeholder="Describe what staff should focus on this week."
                />
              </Field>
            </div>
          </div>

          <div className={sectionClassName}>
            <div className="flex items-center justify-between gap-3">
              <h4 className="text-sm font-semibold text-white">Key Reminders</h4>
              <Button
                type="button"
                variant="ghost"
                size="sm"
                leadingIcon={<Plus size={14} />}
                onClick={editor.addReminder}
                disabled={disabled}
                className="border border-slate-700/60 text-slate-200 hover:bg-slate-700/40"
              >
                Add Reminder
              </Button>
            </div>
            <div className="space-y-2">
              {quiz.keyReminders.map((reminder, index) => (
                <div key={`${index}-${reminder}`} className="flex items-center gap-2">
                  <Input
                    value={reminder}
                    onChange={(event) => editor.updateReminder(index, event.target.value)}
                    disabled={disabled}
                    className={inputClassName}
                    aria-label={`Key reminder ${index + 1}`}
                    placeholder="Add a key reminder."
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    aria-label={`Remove reminder ${index + 1}`}
                    onClick={() => editor.removeReminder(index)}
                    disabled={disabled || quiz.keyReminders.length <= 1}
                    className={iconButtonClassName}
                  >
                    <Trash2 size={15} />
                  </Button>
                </div>
              ))}
            </div>
          </div>

          <div className={sectionClassName}>
            <div className="flex items-center justify-between gap-3">
              <h4 className="text-sm font-semibold text-white">Questions</h4>
              <Button
                type="button"
                variant="ghost"
                size="sm"
                leadingIcon={<Plus size={14} />}
                onClick={editor.addQuestion}
                disabled={disabled}
                className="border border-slate-700/60 text-slate-200 hover:bg-slate-700/40"
              >
                Add Question
              </Button>
            </div>

            <div className="space-y-4">
              {quiz.questions.map((question, questionIndex) => (
                <div
                  key={question.id}
                  className="rounded-xl border border-slate-700/50 bg-slate-900/50 p-4 space-y-4"
                >
                  <div className="flex items-center justify-between gap-3">
                    <h5 className="text-sm font-semibold text-slate-100">Question {questionIndex + 1}</h5>
                    <Button
                      type="button"
                      variant="ghost"
                      aria-label={`Remove question ${questionIndex + 1}`}
                      onClick={() => editor.removeQuestion(questionIndex)}
                      disabled={disabled || quiz.questions.length <= 1}
                      className={iconButtonClassName}
                    >
                      <Trash2 size={15} />
                    </Button>
                  </div>

                  <Field label="Question text">
                    <Textarea
                      value={question.question}
                      onChange={(event) => editor.updateQuestion(questionIndex, { question: event.target.value })}
                      disabled={disabled}
                      className={`${inputClassName} min-h-20`}
                      placeholder="Write the question staff should answer."
                    />
                  </Field>

                  <div className="space-y-2">
                    <div className="flex items-center justify-between gap-3">
                      <span className={labelClassName}>Answers</span>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        leadingIcon={<Plus size={14} />}
                        onClick={() => editor.addQuestionOption(questionIndex)}
                        disabled={disabled}
                        className="border border-slate-700/60 text-slate-200 hover:bg-slate-700/40"
                      >
                        Add Answer
                      </Button>
                    </div>

                    {question.options.map((option, optionIndex) => (
                      <div key={`${question.id}-${optionIndex}`} className="grid gap-2 md:grid-cols-[1fr_160px_40px]">
                        <Input
                          value={option}
                          onChange={(event) =>
                            editor.updateQuestionOption(questionIndex, optionIndex, event.target.value)
                          }
                          disabled={disabled}
                          className={inputClassName}
                          aria-label={`Question ${questionIndex + 1} answer ${optionIndex + 1}`}
                          placeholder={`Answer ${optionIndex + 1}`}
                        />
                        <Button
                          type="button"
                          variant={question.correctIndex === optionIndex ? 'default' : 'ghost'}
                          onClick={() => editor.updateQuestion(questionIndex, { correctIndex: optionIndex })}
                          disabled={disabled}
                          className={question.correctIndex === optionIndex
                            ? 'bg-emerald-500/20 text-emerald-200 border border-emerald-500/30 hover:bg-emerald-500/30'
                            : 'border border-slate-700/60 text-slate-300 hover:bg-slate-700/40'}
                        >
                          Correct
                        </Button>
                        <Button
                          type="button"
                          variant="ghost"
                          aria-label={`Remove answer ${optionIndex + 1}`}
                          onClick={() => editor.removeQuestionOption(questionIndex, optionIndex)}
                          disabled={disabled || question.options.length <= 2}
                          className={iconButtonClassName}
                        >
                          <Trash2 size={15} />
                        </Button>
                      </div>
                    ))}
                  </div>

                  <Field label="Explanation">
                    <Textarea
                      value={question.explanation}
                      onChange={(event) => editor.updateQuestion(questionIndex, { explanation: event.target.value })}
                      disabled={disabled}
                      className={`${inputClassName} min-h-20`}
                      placeholder="Explain why the correct answer is safest."
                    />
                  </Field>
                </div>
              ))}
            </div>
          </div>

          <div className="flex flex-col gap-2 sm:flex-row">
            <Button
              type="submit"
              loading={editor.isSaving}
              disabled={!editor.canSave}
              className="bg-blue-500/20 text-blue-300 border border-blue-500/30 hover:bg-blue-500/30"
            >
              Save Quiz
            </Button>
            <Button
              type="button"
              variant="ghost"
              onClick={editor.reset}
              disabled={disabled}
              className="border border-slate-700/60 text-slate-300 hover:bg-slate-700/40"
            >
              Reset
            </Button>
          </div>
          </form>
        )}
      </CollapsibleContent>

      <ConfirmationDialog
        open={deleteOpen}
        title="Delete QBS safety quiz?"
        description="This will remove the current quiz and key reminders from this tenant's Behavior Management page."
        confirmLabel="Delete quiz"
        loading={editor.isDeleting}
        tone="danger"
        onCancel={() => setDeleteOpen(false)}
        onConfirm={() => {
          void editor.deleteQuiz().then(() => setDeleteOpen(false));
        }}
      />
    </Collapsible>
  );
}

function Field({
  label,
  children,
}: {
  readonly label: string;
  readonly children: ReactNode;
}) {
  return (
    <label className="space-y-2">
      <span className={labelClassName}>{label}</span>
      {children}
    </label>
  );
}
