import { useState } from 'react';
import {
  Stack,
  Title,
  Group,
  Button,
  Badge,
  ActionIcon,
  Modal,
  Text,
  TextInput,
  Paper,
  Card,
  Alert,
  Select,
  NumberInput,
} from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import { useTranslation } from 'react-i18next';
import { IconEdit, IconTrash, IconPlus, IconInfoCircle } from '@tabler/icons-react';
import { notify, useErrorHandler, AdvancedTable, useServerTable, type AdvancedColumn } from '@ema-platform/ui';
import { useGetCertificationsQuery } from '../../certification/api/certification-api';
import {
  useGetQuestionsQuery,
  useCreateQuestionMutation,
  useUpdateQuestionMutation,
  useDeleteQuestionMutation,
} from '../api/question-api';
import type { Question, QuestionForm } from '../types/question';

function QuestionForm({
  editing,
  certOptions,
  isSubmitting,
  onSubmit,
  onCancel,
}: {
  editing: Question | null;
  certOptions: { value: string; label: string }[];
  isSubmitting: boolean;
  onSubmit: (values: {
    certificationId: string;
    titleEn: string;
    titleAm: string;
    form: string;
    points: number;
    days: number;
    hours: number;
    minutes: number;
  }, isEdit: boolean) => void;
  onCancel: () => void;
}) {
  const { t } = useTranslation();
  const [certificationId, setCertificationId] = useState<string | null>(editing?.certificationId ?? null);
  const [titleEn, setTitleEn] = useState(editing?.title?.en ?? '');
  const [titleAm, setTitleAm] = useState(editing?.title?.am ?? '');

  const [form, setForm] = useState<string | null>(editing?.form ?? null);
  const [points, setPoints] = useState<number>(editing?.points ?? 0);
  const [days, setDays] = useState(editing?.time?.days ?? 0);
  const [hours, setHours] = useState(editing?.time?.hours ?? 0);
  const [minutes, setMinutes] = useState(editing?.time?.minutes ?? 0);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!certificationId || !titleEn || !titleAm || !form) {
      notify.error('Please fill all required fields');
      return;
    }
    onSubmit({
        certificationId, titleEn, titleAm, form, points, days, hours, minutes
    }, !!editing);
  };

  return (
    <Paper p="md" withBorder mb="md" radius="md">
      <form onSubmit={handleSubmit}>
        <Stack gap="sm">
          <Select label={t('question.form.certification')} placeholder={t('question.form.selectCertification')} data={certOptions} value={certificationId} onChange={setCertificationId} size="sm" searchable required />
          <TextInput label={t('question.form.titleEn')} placeholder={t('question.form.titleEnPlaceholder')} value={titleEn} onChange={(e) => setTitleEn(e.currentTarget.value)} size="sm" required />
          <TextInput label={t('question.form.titleAm')} placeholder={t('question.form.titleAmPlaceholder')} value={titleAm} onChange={(e) => setTitleAm(e.currentTarget.value)} size="sm" required />
          <Select label={t('question.form.form')} placeholder={t('question.form.selectForm')} data={[{ value: 'ESSAY', label: t('question.form.essay') }, { value: 'CHOICE', label: t('question.form.choice') }]} value={form} onChange={setForm} size="sm" required />
          <NumberInput label={t('question.form.points')} placeholder={t('question.form.pointsPlaceholder')} value={points} onChange={(v) => setPoints(Number(v))} min={0} size="sm" required />
          <Text fz="sm" fw={500}>{t('question.form.timeAllowed')}</Text>
          <Group gap="sm" grow>
            <NumberInput label={t('question.form.days')} value={days} onChange={(v) => setDays(Number(v))} min={0} size="sm" />
            <NumberInput label={t('question.form.hours')} value={hours} onChange={(v) => setHours(Number(v))} min={0} size="sm" />
            <NumberInput label={t('question.form.minutes')} value={minutes} onChange={(v) => setMinutes(Number(v))} min={0} size="sm" />
          </Group>
          <Group justify="flex-end">
            <Button variant="default" onClick={onCancel} size="sm">{t('question.cancel')}</Button>
            <Button type="submit" size="sm" loading={isSubmitting}>{editing ? t('question.update') : t('question.create')}</Button>
          </Group>
        </Stack>
      </form>
    </Paper>
  );
}

export function QuestionPage() {
  const { t, i18n } = useTranslation();
  const locale = i18n.language as 'en' | 'am';
  const { handleError } = useErrorHandler();
  const { data: certRes } = useGetCertificationsQuery();
  const { data, isFetching, isError, refetch } = useGetQuestionsQuery();
  const { setPageIndex, pageSize, paginate } = useServerTable();
  const [createQ, { isLoading: isCreating }] = useCreateQuestionMutation();
  const [updateQ, { isLoading: isUpdating }] = useUpdateQuestionMutation();
  const [deleteQ] = useDeleteQuestionMutation();

  const certifications = certRes?.items ?? [];
  const questions = data?.items ?? [];

  const [editing, setEditing] = useState<Question | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<Question | null>(null);
  const [deleteOpened, { open: openDelete, close: closeDelete }] = useDisclosure(false);
  const [certFilter, setCertFilter] = useState<string | null>(null);

  const certOptions = certifications.filter((c) => c.isActive).map((c) => ({ value: c.id, label: c.name[locale] }));

  const filtered = questions.filter((q) => !certFilter || q.certificationId === certFilter);
  const page = paginate(filtered);

  const getCertName = (id: string) => certifications.find((c) => c.id === id)?.name?.[locale] ?? '-';

  const resetForm = () => { setEditing(null); setShowForm(false); };

  const handleSubmit = async (values: {
    certificationId: string; titleEn: string; titleAm: string;
    form: string; points: number; days: number; hours: number; minutes: number;
  }, isEdit: boolean) => {
    const title = { en: values.titleEn, am: values.titleAm };
    const time = { days: values.days, hours: values.hours, minutes: values.minutes };
    try {
      if (isEdit && editing) {
        await updateQ({ id: editing.id, certificationId: values.certificationId, title, form: values.form as QuestionForm, points: values.points, time }).unwrap();
        notify.success(t('question.updated'));
      } else {
        await createQ({ certificationId: values.certificationId, title, description: { en: '', am: '' }, form: values.form as QuestionForm, points: values.points, time }).unwrap();
        notify.success(t('question.created'));
      }
      resetForm();
    } catch (e) {
      handleError(e);
    }
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await deleteQ(deleteTarget.id).unwrap();
      notify.success(t('question.deleted'));
      closeDelete();
      setDeleteTarget(null);
    } catch (e) {
      handleError(e);
    }
  };

  if (isError) return <Alert icon={<IconInfoCircle size={16} />} color="red" title={t('question.loadError')} />;

  const columns: AdvancedColumn<Question>[] = [
    {
      header: t('question.columns.title'),
      cell: ({ row }) => <Text fz="sm" maw={300} lineClamp={2}>{row.original.title[locale]}</Text>,
    },
    {
      header: t('question.columns.certification'),
      cell: ({ row }) => <Text fz="sm">{getCertName(row.original.certificationId)}</Text>,
    },
    {
      header: t('question.columns.form'),
      cell: ({ row }) => (
        <Badge size="sm" variant="light" color={row.original.form === 'ESSAY' ? 'blue' : 'violet'}>
          {t(`question.form.${row.original.form === 'ESSAY' ? 'essay' : 'choice'}`)}
        </Badge>
      ),
    },
    {
      header: t('question.columns.points'),
      cell: ({ row }) => <Text fz="sm" fw={600}>{row.original.points}</Text>,
    },
    {
      header: t('question.columns.status'),
      cell: ({ row }) => (
        <Badge size="sm" variant="light" color={row.original.isActive ? 'teal' : 'gray'}>
          {row.original.isActive ? t('question.status.active') : t('question.status.inactive')}
        </Badge>
      ),
    },
    {
      header: '',
      label: t('question.columns.actions', 'Actions'),
      cell: ({ row }) => (
        <Group gap="xs">
          <ActionIcon variant="subtle" color="blue" size="sm" onClick={() => { setEditing(row.original); setShowForm(true); }}>
            <IconEdit size={14} />
          </ActionIcon>
          <ActionIcon variant="subtle" color="red" size="sm" onClick={() => { setDeleteTarget(row.original); openDelete(); }}>
            <IconTrash size={14} />
          </ActionIcon>
        </Group>
      ),
    },
  ];

  return (
    <Stack gap="lg">
      <Group justify="space-between" align="flex-end">
        <Title order={2}>{t('question.title')}</Title>
        {!showForm && (
          <Button variant="light" leftSection={<IconPlus size={16} />} onClick={() => setShowForm(true)} size="sm">
            {t('question.addQuestion')}
          </Button>
        )}
      </Group>

      {showForm && (
        <QuestionForm
          editing={editing}
          certOptions={certOptions}
          isSubmitting={isCreating || isUpdating}
          onSubmit={handleSubmit}
          onCancel={resetForm}
        />
      )}

      <Card withBorder padding={0}>
        <Group p="md" justify="space-between" wrap="wrap" gap="sm">
          <Text fw={600}>{t('question.pool')}</Text>
          <Select
            placeholder={t('question.filterByCertification')}
            data={[{ value: '', label: 'All' }, ...certOptions]}
            value={certFilter}
            onChange={(v) => { setCertFilter(v ?? null); setPageIndex(0); }}
            size="sm"
            style={{ width: 280 }}
            clearable
          />
        </Group>
        <AdvancedTable
          columns={columns}
          data={page.rows}
          tableName={t('question.title')}
          itemCount={page.itemCount}
          pageIndex={page.pageIndex}
          onPageChange={setPageIndex}
          pageSize={pageSize}
          refresh={refetch}
          isLoading={isFetching}
          emptyText={t('question.noQuestions')}
        />
      </Card>

      <Modal opened={deleteOpened} onClose={closeDelete} title={t('question.confirmDelete')} size="sm">
        <Text mb="md">{t('question.deleteConfirmText')}</Text>
        <Group justify="flex-end">
          <Button variant="default" onClick={closeDelete} size="sm">{t('question.cancel')}</Button>
          <Button color="red" onClick={handleDelete} size="sm">{t('question.delete')}</Button>
        </Group>
      </Modal>
    </Stack>
  );
}
