import { useState } from 'react';
import {
  Typography,
  Card,
  Form,
  Input,
  Select,
  Button,
  Alert,
  Space,
  Result,
  Spin,
  Divider,
} from 'antd';
import { showSuccess, showError } from '@/lib/errorHandling';
import {
  ToolOutlined,
  ReloadOutlined,
  LockOutlined,
  DashboardOutlined,
} from '@ant-design/icons';
import { useUser } from '@/stores/authStore';
import { useCanAdmin } from '@/stores/companyStore';
import { useMutation, useQuery } from '@tanstack/react-query';
import { graphqlClient } from '@/api/client';
import { gql } from 'graphql-request';

const { Title, Text, Paragraph } = Typography;


// Derive backend base URL from GraphQL endpoint
const GRAPHQL_ENDPOINT = import.meta.env.VITE_GRAPHQL_ENDPOINT || 'http://localhost:5000/graphql';
const BACKEND_BASE_URL = GRAPHQL_ENDPOINT.replace('/graphql', '');

// GraphQL queries and mutations
const LIST_READ_MODEL_TYPES = gql`
  mutation ListReadModelTypes {
    listReadModelTypes
  }
`;

const REPOPULATE_READ_MODEL = gql`
  mutation RepopulateReadModel($aggregateId: String!, $readModelType: String!) {
    repopulateReadModel(aggregateId: $aggregateId, readModelType: $readModelType)
  }
`;

interface ListReadModelTypesResponse {
  listReadModelTypes: string[];
}

interface RepopulateReadModelResponse {
  repopulateReadModel: boolean;
}

export default function Admin() {
  const user = useUser();
  const [form] = Form.useForm();
  const [lastResult, setLastResult] = useState<{ success: boolean; message: string } | null>(null);

  // Check if user has Owner role for the active company
  const isAdmin = useCanAdmin();

  // Fetch available read model types
  const { data: readModelTypes, isLoading: typesLoading } = useQuery({
    queryKey: ['readModelTypes'],
    queryFn: async () => {
      const response = await graphqlClient.request<ListReadModelTypesResponse>(LIST_READ_MODEL_TYPES);
      return response.listReadModelTypes;
    },
    enabled: isAdmin,
  });

  // Repopulate mutation
  const repopulateMutation = useMutation({
    mutationFn: async (variables: { aggregateId: string; readModelType: string }) => {
      return graphqlClient.request<RepopulateReadModelResponse>(REPOPULATE_READ_MODEL, variables);
    },
    onSuccess: (data, variables) => {
      if (data.repopulateReadModel) {
        setLastResult({
          success: true,
          message: `Read model "${variables.readModelType}" for aggregate "${variables.aggregateId}" er blevet genopbygget.`,
        });
        showSuccess('Read model genopbygget!');
        form.resetFields();
      } else {
        setLastResult({
          success: false,
          message: 'Genopbygning returnerede false - check logs for detaljer.',
        });
      }
    },
    onError: (error: Error) => {
      setLastResult({
        success: false,
        message: `Fejl: ${error.message}`,
      });
      showError('Genopbygning fejlede');
    },
  });

  const handleRepopulate = async () => {
    try {
      const values = await form.validateFields();
      setLastResult(null);
      repopulateMutation.mutate(values);
    } catch {
      // Validation error - handled by form
    }
  };

  // Show access denied if not admin
  if (!isAdmin) {
    return (
      <Result
        status="403"
        icon={<LockOutlined />}
        title="Adgang nægtet"
        subTitle="Du har ikke adgang til admin-området. Kun autoriserede administratorer kan tilgå denne side."
        extra={
          <Text type="secondary">
            Logget ind som: {user?.email || 'Ukendt'}
          </Text>
        }
      />
    );
  }

  return (
    <div>
      {/* Header */}
      <div style={{ marginBottom: 16 }}>
        <Title level={4} style={{ margin: 0 }}>
          <ToolOutlined /> Administration
        </Title>
        <Text type="secondary">Systemværktøjer til fejlfinding og vedligeholdelse</Text>
      </div>

      <Alert
        message="Advarsel"
        description="Disse værktøjer er beregnet til fejlfinding og kan påvirke systemets tilstand. Brug dem med forsigtighed."
        type="warning"
        showIcon
        style={{ marginBottom: 24 }}
      />

      {/* Read Model Repair */}
      <Card title="Read Model Repair">
        <Paragraph type="secondary">
          Hvis en read model er ude af sync med event store, kan du genopbygge den ved at afspille alle events for et specifikt aggregat.
          Dette er nyttigt når data vises forkert, eller handlinger fejler på grund af inkonsistent tilstand.
        </Paragraph>

        <Divider />

        {typesLoading ? (
          <Spin tip="Henter read model typer..." />
        ) : (
          <Form
            form={form}
            layout="vertical"
            style={{ maxWidth: 600 }}
          >
            <Form.Item
              name="readModelType"
              label="Read Model Type"
              rules={[{ required: true, message: 'Vælg en read model type' }]}
            >
              <Select
                placeholder="Vælg read model type"
                options={readModelTypes?.map(type => ({
                  value: type,
                  label: type,
                }))}
              />
            </Form.Item>

            <Form.Item
              name="aggregateId"
              label="Aggregate ID"
              rules={[{ required: true, message: 'Indtast aggregate ID' }]}
              extra="F.eks. 'journalentrydraft-abc123-def456-...' eller 'company-xyz789-...'"
            >
              <Input
                placeholder="journalentrydraft-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
                style={{ fontFamily: 'monospace' }}
              />
            </Form.Item>

            <Space>
              <Button
                type="primary"
                icon={<ReloadOutlined />}
                onClick={handleRepopulate}
                loading={repopulateMutation.isPending}
              >
                Genopbyg Read Model
              </Button>
              <Button onClick={() => { form.resetFields(); setLastResult(null); }}>
                Nulstil
              </Button>
            </Space>
          </Form>
        )}

        {lastResult && (
          <Alert
            style={{ marginTop: 16 }}
            message={lastResult.success ? 'Succes' : 'Fejl'}
            description={lastResult.message}
            type={lastResult.success ? 'success' : 'error'}
            showIcon
          />
        )}

        <Divider />

        <Title level={5}>Tilgængelige Read Model Typer</Title>
        <Paragraph type="secondary" style={{ fontSize: 12 }}>
          {readModelTypes?.join(', ') || 'Indlæser...'}
        </Paragraph>
      </Card>

      {/* Background Jobs Dashboard */}
      <Card title="Baggrundsjobs" style={{ marginTop: 24 }}>
        <Paragraph type="secondary">
          Hangfire dashboard giver overblik over baggrundsjobs, køer, og fejlede opgaver i systemet.
        </Paragraph>
        <Button
          type="primary"
          icon={<DashboardOutlined />}
          href={`${BACKEND_BASE_URL}/hangfire`}
          target="_blank"
          rel="noopener noreferrer"
        >
          Åbn Hangfire Dashboard
        </Button>
      </Card>
    </div>
  );
}
