import { useState, type ReactNode } from 'react';
import { Plus, Save, Trash2, X } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { NativeSelect } from '@/components/ui/native-select';
import { Textarea } from '@/components/ui/textarea';
import type {
  EsaFaqItem,
  EsaFundingContent,
  EsaParentConversationReference,
  EsaResource,
  EsaSchoolImpactItem,
  EsaStaffRoleItem,
} from '@/shared/types/esaFunding';

interface EsaSectionEditorProps {
  readonly content: EsaFundingContent;
  readonly isSaving: boolean;
  readonly onSave: (content: EsaFundingContent, sectionName: string) => Promise<void>;
}

interface InlineEditorShellProps {
  readonly title: string;
  readonly description: string;
  readonly isSaving: boolean;
  readonly onAdd?: () => void;
  readonly onSave: () => Promise<void>;
  readonly children: ReactNode;
}

function createId(prefix: string): string {
  return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}

function textInputId(section: string, id: string, field: string): string {
  return `esa-${section}-${id}-${field}`;
}

function InlineEditorShell({
  title,
  description,
  isSaving,
  onAdd,
  onSave,
  children,
}: InlineEditorShellProps) {
  const [isOpen, setIsOpen] = useState(false);

  async function submitForm() {
    await onSave();
    setIsOpen(false);
  }

  return (
    <div className="mt-4 rounded-xl border border-slate-700/60 bg-slate-950/35">
      <div className="flex flex-col gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <p className="text-sm font-semibold text-white">{title}</p>
          <p className="text-xs text-slate-400">{description}</p>
        </div>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={() => setIsOpen((current) => !current)}
          leadingIcon={isOpen ? <X size={14} /> : undefined}
        >
          {isOpen ? 'Cancel' : 'Edit'}
        </Button>
      </div>

      {isOpen ? (
        <form
          className="space-y-4 border-t border-slate-700/60 p-4"
          onSubmit={(event) => {
            event.preventDefault();
            void submitForm();
          }}
        >
          {onAdd ? (
            <div className="flex justify-end">
              <Button type="button" variant="ghost" size="sm" onClick={onAdd} leadingIcon={<Plus size={14} />}>
                Add
              </Button>
            </div>
          ) : null}
          <div className="space-y-3">{children}</div>
          <div className="flex justify-end">
            <Button type="submit" size="sm" loading={isSaving} leadingIcon={<Save size={14} />}>
              Save section
            </Button>
          </div>
        </form>
      ) : null}
    </div>
  );
}

function DeleteButton({ onClick }: { readonly onClick: () => void }) {
  return (
    <Button
      type="button"
      variant="ghost"
      size="icon"
      onClick={onClick}
      aria-label="Delete item"
      className="text-rose-300 hover:text-rose-200"
    >
      <Trash2 size={16} />
    </Button>
  );
}

export function EsaFundingSchoolImpactEditor({
  content,
  isSaving,
  onSave,
}: EsaSectionEditorProps) {
  const [items, setItems] = useState<readonly EsaSchoolImpactItem[]>(content.schoolImpactItems);

  function updateItem(id: string, text: string) {
    setItems((current) => current.map((item) => (item.id === id ? { ...item, text } : item)));
  }

  function addItem() {
    setItems((current) => [...current, { id: createId('impact'), text: '' }]);
  }

  function deleteItem(id: string) {
    setItems((current) => current.filter((item) => item.id !== id));
  }

  return (
    <InlineEditorShell
      title="Edit school impact"
      description="Manage the points shown in this section."
      isSaving={isSaving}
      onAdd={addItem}
      onSave={() => onSave({ ...content, schoolImpactItems: items }, 'Why This Matters for Our School')}
    >
      {items.map((item) => (
        <div key={item.id} className="flex gap-2">
          <Input
            id={textInputId('impact', item.id, 'text')}
            value={item.text}
            onChange={(event) => updateItem(item.id, event.target.value)}
            aria-label="School impact item"
          />
          <DeleteButton onClick={() => deleteItem(item.id)} />
        </div>
      ))}
    </InlineEditorShell>
  );
}

export function EsaFundingStaffRoleEditor({
  content,
  isSaving,
  onSave,
}: EsaSectionEditorProps) {
  const [items, setItems] = useState<readonly EsaStaffRoleItem[]>(content.staffRoleItems);

  function updateItem(id: string, patch: Partial<EsaStaffRoleItem>) {
    setItems((current) => current.map((item) => (item.id === id ? { ...item, ...patch } : item)));
  }

  function addItem() {
    setItems((current) => [...current, { id: createId('staff'), title: '', description: '' }]);
  }

  function deleteItem(id: string) {
    setItems((current) => current.filter((item) => item.id !== id));
  }

  return (
    <InlineEditorShell
      title="Edit staff guidance"
      description="Manage the staff-only guidance shown here."
      isSaving={isSaving}
      onAdd={addItem}
      onSave={() => onSave({ ...content, staffRoleItems: items }, 'Your Role as Staff')}
    >
      {items.map((item) => (
        <div key={item.id} className="grid gap-2 rounded-xl border border-slate-700/50 p-3">
          <Label htmlFor={textInputId('staff', item.id, 'title')}>Title</Label>
          <Input
            id={textInputId('staff', item.id, 'title')}
            value={item.title}
            onChange={(event) => updateItem(item.id, { title: event.target.value })}
          />
          <Label htmlFor={textInputId('staff', item.id, 'description')}>Description</Label>
          <Textarea
            id={textInputId('staff', item.id, 'description')}
            value={item.description}
            onChange={(event) => updateItem(item.id, { description: event.target.value })}
          />
          <DeleteButton onClick={() => deleteItem(item.id)} />
        </div>
      ))}
    </InlineEditorShell>
  );
}

export function EsaFundingFaqEditor({
  content,
  isSaving,
  onSave,
}: EsaSectionEditorProps) {
  const [items, setItems] = useState<readonly EsaFaqItem[]>(content.faqs);

  function updateItem(id: string, patch: Partial<EsaFaqItem>) {
    setItems((current) => current.map((item) => (item.id === id ? { ...item, ...patch } : item)));
  }

  function addItem() {
    setItems((current) => [...current, { id: createId('faq'), question: '', answer: '', audience: 'all' }]);
  }

  function deleteItem(id: string) {
    setItems((current) => current.filter((item) => item.id !== id));
  }

  return (
    <InlineEditorShell
      title="Edit FAQ"
      description="Manage questions and their student/guardian visibility."
      isSaving={isSaving}
      onAdd={addItem}
      onSave={() => onSave({ ...content, faqs: items }, 'Frequently Asked Questions')}
    >
      {items.map((item) => (
        <div key={item.id} className="grid gap-2 rounded-xl border border-slate-700/50 p-3">
          <Label htmlFor={textInputId('faq', item.id, 'question')}>Question</Label>
          <Input
            id={textInputId('faq', item.id, 'question')}
            value={item.question}
            onChange={(event) => updateItem(item.id, { question: event.target.value })}
          />
          <Label htmlFor={textInputId('faq', item.id, 'answer')}>Answer</Label>
          <Textarea
            id={textInputId('faq', item.id, 'answer')}
            value={item.answer}
            onChange={(event) => updateItem(item.id, { answer: event.target.value })}
          />
          <Label htmlFor={textInputId('faq', item.id, 'audience')}>Audience</Label>
          <NativeSelect
            id={textInputId('faq', item.id, 'audience')}
            value={item.audience}
            onChange={(event) => updateItem(item.id, {
              audience: event.target.value === 'staff' ? 'staff' : 'all',
            })}
          >
            <option value="all">Show for everybody</option>
            <option value="staff">Hide from students and guardians</option>
          </NativeSelect>
          <DeleteButton onClick={() => deleteItem(item.id)} />
        </div>
      ))}
    </InlineEditorShell>
  );
}

export function EsaFundingQuickReferenceEditor({
  content,
  isSaving,
  onSave,
}: EsaSectionEditorProps) {
  const [items, setItems] = useState<readonly EsaParentConversationReference[]>(content.parentConversationReferences);

  function updateItem(id: string, patch: Partial<EsaParentConversationReference>) {
    setItems((current) => current.map((item) => (item.id === id ? { ...item, ...patch } : item)));
  }

  function addItem() {
    setItems((current) => [...current, {
      id: createId('parent-reference'),
      question: '',
      answer: '',
    }]);
  }

  function deleteItem(id: string) {
    setItems((current) => current.filter((item) => item.id !== id));
  }

  return (
    <InlineEditorShell
      title="Edit quick reference"
      description="Manage the staff-only parent conversation references."
      isSaving={isSaving}
      onAdd={addItem}
      onSave={() => onSave({ ...content, parentConversationReferences: items }, 'Quick Reference for Parent Conversations')}
    >
      {items.map((item, index) => (
        <div key={item.id} className="grid gap-2 rounded-xl border border-slate-700/50 p-3">
          <div className="flex items-center justify-between gap-3">
            <p className="text-sm font-semibold text-slate-200">Parent conversation reference {index + 1}</p>
            <DeleteButton onClick={() => deleteItem(item.id)} />
          </div>
          <Label htmlFor={textInputId('parent-reference', item.id, 'question')}>Question</Label>
          <Input
            id={textInputId('parent-reference', item.id, 'question')}
            value={item.question}
            onChange={(event) => updateItem(item.id, { question: event.target.value })}
            placeholder="If a parent asks about ESA, here is a simple way to explain it:"
          />
          <Label htmlFor={textInputId('parent-reference', item.id, 'answer')}>Answer</Label>
          <Textarea
            id={textInputId('parent-reference', item.id, 'answer')}
            value={item.answer}
            onChange={(event) => updateItem(item.id, { answer: event.target.value })}
            placeholder="ESA stands for Empowerment Scholarship Account..."
          />
        </div>
      ))}
    </InlineEditorShell>
  );
}

export function EsaFundingResourcesEditor({
  content,
  isSaving,
  onSave,
}: EsaSectionEditorProps) {
  const [items, setItems] = useState<readonly EsaResource[]>(content.resources);

  function updateItem(id: string, patch: Partial<EsaResource>) {
    setItems((current) => current.map((item) => (item.id === id ? { ...item, ...patch } : item)));
  }

  function addItem() {
    setItems((current) => [...current, { id: createId('resource'), title: '', description: '', url: '#' }]);
  }

  function deleteItem(id: string) {
    setItems((current) => current.filter((item) => item.id !== id));
  }

  return (
    <InlineEditorShell
      title="Edit resources"
      description="Manage the links shown in this section."
      isSaving={isSaving}
      onAdd={addItem}
      onSave={() => onSave({ ...content, resources: items }, 'Helpful Resources')}
    >
      {items.map((item) => (
        <div key={item.id} className="grid gap-2 rounded-xl border border-slate-700/50 p-3">
          <Label htmlFor={textInputId('resource', item.id, 'title')}>Title</Label>
          <Input
            id={textInputId('resource', item.id, 'title')}
            value={item.title}
            onChange={(event) => updateItem(item.id, { title: event.target.value })}
          />
          <Label htmlFor={textInputId('resource', item.id, 'description')}>Description</Label>
          <Input
            id={textInputId('resource', item.id, 'description')}
            value={item.description}
            onChange={(event) => updateItem(item.id, { description: event.target.value })}
          />
          <Label htmlFor={textInputId('resource', item.id, 'url')}>URL</Label>
          <Input
            id={textInputId('resource', item.id, 'url')}
            value={item.url}
            onChange={(event) => updateItem(item.id, { url: event.target.value })}
          />
          <DeleteButton onClick={() => deleteItem(item.id)} />
        </div>
      ))}
    </InlineEditorShell>
  );
}
