import React, { useMemo, useState } from 'react';
import styled from 'styled-components';
import { isAxiosError } from 'axios';
import { AdminPageShell } from '@/features/admin/components/AdminPageShell';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useLocale } from '@/app/providers/LocaleProvider';
import { PERMISSIONS } from '@/features/auth/constants/permissions';
import { usePermissions } from '@/features/auth/hooks/usePermissions';
import { useAuthStore } from '@/features/auth/store/authStore';
import { useTicketDepartments } from '@/features/tickets/hooks/useTicketDepartments';
import { AppLayout } from '@/shared/components/layout/AppLayout';
import {
  Button,
  Input,
  Modal,
  Select,
  Table,
  Th,
  Td,
  Tr,
  AdminPanel,
  TableWrap,
  PanelLoadingState,
  PanelMessage,
  ActionsTd,
} from '@/shared/components/ui';
import {
  customizeNotificationTemplate,
  listNotificationTemplates,
  resetNotificationTemplate,
  updateNotificationTemplate,
  type NotificationTemplateRecord,
} from '@/features/admin/services/notificationTemplateAdminService';
import { AdminActionsHeader } from '@/features/admin/components/AdminRowActions';

const RowActions = styled.div`
  display: flex;
  gap: ${({ theme }) => theme.spacing[2]};
  justify-content: flex-end;
  flex-wrap: wrap;
`;

const AdminNotificationTemplatesPage: React.FC = () => {
  const { t } = useLocale();
  const user = useAuthStore((state) => state.user);
  const { can, isSuperAdmin } = usePermissions();
  const {
    departments,
    departmentId,
    setDepartmentId,
    companyId,
    setCompanyId,
    companies,
    isLoadingCompanies,
    isLoadingDepartments,
    hasCompany,
    hasDepartments,
  } = useTicketDepartments();
  const queryClient = useQueryClient();
  const [editing, setEditing] = useState<NotificationTemplateRecord | null>(null);
  const [form, setForm] = useState({
    subject_en: '',
    subject_ar: '',
    body_en: '',
    body_ar: '',
    is_active: true,
  });

  const canEditGlobalTemplates =
    isSuperAdmin || can(PERMISSIONS.GLOBAL_SETTINGS_MANAGE) || can(PERMISSIONS.COMPANY_SETTINGS_MANAGE);

  const companyOptions = useMemo(
    () => [
      { value: '', label: t('admin:users.selectCompany') },
      ...companies.map((company) => ({ value: company.id, label: company.name })),
    ],
    [companies, t],
  );

  const departmentOptions = useMemo(
    () => [
      { value: '', label: t('admin:users.selectDepartment') },
      ...departments.map((department) => ({ value: department.id, label: department.name })),
    ],
    [departments, t],
  );

  const lockedCompanyLabel = user?.company?.name ?? '';

  const templatesQuery = useQuery({
    queryKey: ['admin', 'notification-templates', departmentId],
    queryFn: () => listNotificationTemplates(departmentId || undefined),
    enabled: Boolean(departmentId),
  });

  const saveMutation = useMutation({
    mutationFn: () => {
      if (!editing) {
        throw new Error('No template selected');
      }
      return updateNotificationTemplate(editing.id, form);
    },
    onSuccess: async () => {
      setEditing(null);
      await queryClient.invalidateQueries({
        queryKey: ['admin', 'notification-templates', departmentId],
      });
    },
  });

  const customizeMutation = useMutation({
    mutationFn: (template: NotificationTemplateRecord) => {
      if (!departmentId) {
        throw new Error('Department is required');
      }
      return customizeNotificationTemplate(template.id, departmentId);
    },
    onSuccess: async (override) => {
      await queryClient.invalidateQueries({
        queryKey: ['admin', 'notification-templates', departmentId],
      });
      openEdit(override);
    },
  });

  const resetMutation = useMutation({
    mutationFn: (id: string) => resetNotificationTemplate(id),
    onSuccess: async () => {
      await queryClient.invalidateQueries({
        queryKey: ['admin', 'notification-templates', departmentId],
      });
    },
  });

  const openEdit = (template: NotificationTemplateRecord) => {
    setEditing(template);
    setForm({
      subject_en: template.subject_en,
      subject_ar: template.subject_ar,
      body_en: template.body_en,
      body_ar: template.body_ar,
      is_active: template.is_active,
    });
  };

  const canCustomizeTemplate = (template: NotificationTemplateRecord) =>
    template.is_global && Boolean(departmentId) && !canEditGlobalTemplates;

  const canEditTemplate = (template: NotificationTemplateRecord) =>
    !template.is_global || canEditGlobalTemplates;

  const isForbidden =
    templatesQuery.isError &&
    isAxiosError(templatesQuery.error) &&
    templatesQuery.error.response?.status === 403;

  return (
    <AppLayout>
      <AdminPageShell
        title={t('admin:templates.title')}
        subtitle={t('admin:templates.subtitle')}
        backLabel={t('settings:title')}
        toolbar={
          <>
            {isSuperAdmin ? (
              <Select
                label={t('admin:users.filters.company')}
                value={companyId}
                onChange={(event) => setCompanyId(event.target.value)}
                options={companyOptions}
                disabled={isLoadingCompanies}
                style={{ minWidth: 220 }}
              />
            ) : (
              <Input
                label={t('admin:users.filters.company')}
                value={lockedCompanyLabel}
                readOnly
                style={{ minWidth: 220 }}
              />
            )}
            <Select
              label={t('admin:categories.department')}
              value={departmentId}
              onChange={(event) => setDepartmentId(event.target.value)}
              options={departmentOptions}
              disabled={isLoadingDepartments || !hasCompany || !hasDepartments}
              style={{ minWidth: 240 }}
            />
          </>
        }
      >
        <AdminPanel>
          {isSuperAdmin && !hasCompany ? (
            <p style={{ margin: 0 }}>{t('admin:departments.companyRequired')}</p>
          ) : !departmentId ? (
            <p style={{ margin: 0 }}>{t('admin:users.selectDepartment')}</p>
          ) : isForbidden ? (
            <PanelMessage $variant="error">{t('admin:states.forbidden')}</PanelMessage>
          ) : templatesQuery.isLoading ? (
            <PanelLoadingState />
          ) : (templatesQuery.data?.length ?? 0) === 0 ? (
            <p style={{ margin: 0 }}>{t('admin:states.empty')}</p>
          ) : (
            <TableWrap>
              <Table>
                <thead>
                  <tr>
                    <Th>{t('admin:templates.type')}</Th>
                    <Th>{t('admin:templates.channel')}</Th>
                    <Th>{t('admin:templates.scope')}</Th>
                    <AdminActionsHeader />
                  </tr>
                </thead>
                <tbody>
                  {templatesQuery.data?.map((template) => (
                    <Tr key={template.id}>
                      <Td>{template.type}</Td>
                      <Td>{template.channel}</Td>
                      <Td>
                        {template.is_global
                          ? t('admin:templates.global')
                          : t('admin:templates.departmentOverride')}
                      </Td>
                      <ActionsTd>
                        <RowActions>
                          {canCustomizeTemplate(template) ? (
                            <Button
                              size="sm"
                              variant="primary"
                              loading={customizeMutation.isPending}
                              onClick={() => customizeMutation.mutate(template)}
                            >
                              {t('admin:templates.customize')}
                            </Button>
                          ) : null}
                          {canEditTemplate(template) ? (
                            <Button size="sm" variant="secondary" onClick={() => openEdit(template)}>
                              {t('common:actions.edit')}
                            </Button>
                          ) : null}
                          {!template.is_global ? (
                            <Button
                              size="sm"
                              variant="outline"
                              loading={resetMutation.isPending}
                              onClick={() => resetMutation.mutate(template.id)}
                            >
                              {t('admin:templates.reset')}
                            </Button>
                          ) : null}
                        </RowActions>
                      </ActionsTd>
                    </Tr>
                  ))}
                </tbody>
              </Table>
            </TableWrap>
          )}
        </AdminPanel>
      </AdminPageShell>

      <Modal
        isOpen={Boolean(editing)}
        onClose={() => setEditing(null)}
        title={t('admin:templates.editTitle')}
        footer={
          <>
            <Button variant="secondary" onClick={() => setEditing(null)}>
              {t('common:actions.cancel')}
            </Button>
            <Button variant="primary" loading={saveMutation.isPending} onClick={() => saveMutation.mutate()}>
              {t('common:actions.save')}
            </Button>
          </>
        }
      >
        {editing && (
          <>
            <p style={{ textAlign: 'start', marginTop: 0 }}>
              {t('admin:templates.variables')}: {editing.variables.join(', ')}
            </p>
            <Input
              label={t('admin:templates.subjectEn')}
              value={form.subject_en}
              onChange={(e) => setForm((p) => ({ ...p, subject_en: e.target.value }))}
              fullWidth
            />
            <Input
              label={t('admin:templates.subjectAr')}
              value={form.subject_ar}
              onChange={(e) => setForm((p) => ({ ...p, subject_ar: e.target.value }))}
              fullWidth
            />
            <Input
              label={t('admin:templates.bodyEn')}
              value={form.body_en}
              onChange={(e) => setForm((p) => ({ ...p, body_en: e.target.value }))}
              fullWidth
            />
            <Input
              label={t('admin:templates.bodyAr')}
              value={form.body_ar}
              onChange={(e) => setForm((p) => ({ ...p, body_ar: e.target.value }))}
              fullWidth
            />
            <label style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <input
                type="checkbox"
                checked={form.is_active}
                onChange={(e) => setForm((p) => ({ ...p, is_active: e.target.checked }))}
              />
              {t('admin:templates.active')}
            </label>
          </>
        )}
      </Modal>
    </AppLayout>
  );
};

export default AdminNotificationTemplatesPage;
