import { z } from 'zod'
import { TRPCError } from '@trpc/server'
import { Prisma } from '@prisma/client'
import { router, adminProcedure } from '../trpc'
import {
  testTypeformConnection,
  getTypeformSchema,
  getAllTypeformResponses,
  responseToObject,
} from '@/lib/typeform'

export const typeformImportRouter = router({
  /**
   * Test connection to Typeform API
   */
  testConnection: adminProcedure
    .input(
      z.object({
        apiKey: z.string().min(1),
      })
    )
    .mutation(async ({ input }) => {
      return testTypeformConnection(input.apiKey)
    }),

  /**
   * Get form schema (questions/fields) for mapping
   */
  getFormSchema: adminProcedure
    .input(
      z.object({
        apiKey: z.string().min(1),
        formId: z.string().min(1),
      })
    )
    .query(async ({ input }) => {
      try {
        return await getTypeformSchema(input.apiKey, input.formId)
      } catch (error) {
        throw new TRPCError({
          code: 'BAD_REQUEST',
          message:
            error instanceof Error
              ? error.message
              : 'Failed to fetch form schema',
        })
      }
    }),

  /**
   * Preview responses from Typeform
   */
  previewResponses: adminProcedure
    .input(
      z.object({
        apiKey: z.string().min(1),
        formId: z.string().min(1),
        limit: z.number().int().min(1).max(10).default(5),
      })
    )
    .query(async ({ input }) => {
      try {
        const schema = await getTypeformSchema(input.apiKey, input.formId)
        const responses = await getAllTypeformResponses(
          input.apiKey,
          input.formId,
          input.limit
        )

        // Convert responses to flat objects for preview
        const records = responses.map((r) => responseToObject(r, schema.fields))

        return {
          records,
          count: records.length,
          formTitle: schema.title,
        }
      } catch (error) {
        throw new TRPCError({
          code: 'BAD_REQUEST',
          message:
            error instanceof Error
              ? error.message
              : 'Failed to fetch responses from Typeform',
        })
      }
    }),

  /**
   * Import projects from Typeform responses
   */
  importProjects: adminProcedure
    .input(
      z.object({
        apiKey: z.string().min(1),
        formId: z.string().min(1),
        roundId: z.string(),
        // Field mappings: Typeform field title -> Project field
        mappings: z.object({
          title: z.string(), // Required
          teamName: z.string().optional(),
          description: z.string().optional(),
          tags: z.string().optional(), // Multi-select or text field
          email: z.string().optional(), // For tracking submission email
        }),
        // Store unmapped columns in metadataJson
        includeUnmappedInMetadata: z.boolean().default(true),
      })
    )
    .mutation(async ({ ctx, input }) => {
      // Verify round exists
      const round = await ctx.prisma.round.findUniqueOrThrow({
        where: { id: input.roundId },
      })

      // Fetch form schema and all responses
      const schema = await getTypeformSchema(input.apiKey, input.formId)
      const responses = await getAllTypeformResponses(input.apiKey, input.formId)

      if (responses.length === 0) {
        return { imported: 0, skipped: 0, errors: [] }
      }

      const results = {
        imported: 0,
        skipped: 0,
        errors: [] as Array<{ responseId: string; error: string }>,
      }

      // Process each response
      for (const response of responses) {
        try {
          const record = responseToObject(response, schema.fields)

          // Get mapped values
          const title = record[input.mappings.title]

          if (!title || typeof title !== 'string' || !title.trim()) {
            results.errors.push({
              responseId: response.response_id,
              error: 'Missing or invalid title',
            })
            results.skipped++
            continue
          }

          const teamName = input.mappings.teamName
            ? record[input.mappings.teamName]
            : null

          const description = input.mappings.description
            ? record[input.mappings.description]
            : null

          let tags: string[] = []
          if (input.mappings.tags) {
            const tagsValue = record[input.mappings.tags]
            if (Array.isArray(tagsValue)) {
              tags = tagsValue.filter((t): t is string => typeof t === 'string')
            } else if (typeof tagsValue === 'string') {
              tags = tagsValue.split(',').map((t) => t.trim()).filter(Boolean)
            }
          }

          // Build metadata from unmapped columns
          let metadataJson: Record<string, unknown> | null = null
          if (input.includeUnmappedInMetadata) {
            const mappedKeys = new Set([
              input.mappings.title,
              input.mappings.teamName,
              input.mappings.description,
              input.mappings.tags,
              input.mappings.email,
              '_response_id',
              '_submitted_at',
            ].filter(Boolean))

            metadataJson = {}
            for (const [key, value] of Object.entries(record)) {
              if (!mappedKeys.has(key) && value !== null && value !== undefined) {
                metadataJson[key] = value
              }
            }

            // Add submission email if mapped
            if (input.mappings.email) {
              const email = record[input.mappings.email]
              if (email) {
                metadataJson._submissionEmail = email
              }
            }

            // Add submission timestamp
            metadataJson._submittedAt = response.submitted_at

            if (Object.keys(metadataJson).length === 0) {
              metadataJson = null
            }
          }

          // Create project
          await ctx.prisma.project.create({
            data: {
              roundId: round.id,
              title: String(title).trim(),
              teamName: typeof teamName === 'string' ? teamName.trim() : null,
              description: typeof description === 'string' ? description : null,
              tags,
              metadataJson: metadataJson as Prisma.InputJsonValue ?? undefined,
              externalIdsJson: {
                typeformResponseId: response.response_id,
                typeformFormId: input.formId,
              } as Prisma.InputJsonValue,
              status: 'SUBMITTED',
            },
          })

          results.imported++
        } catch (error) {
          results.errors.push({
            responseId: response.response_id,
            error: error instanceof Error ? error.message : 'Unknown error',
          })
          results.skipped++
        }
      }

      // Audit log
      await ctx.prisma.auditLog.create({
        data: {
          userId: ctx.user.id,
          action: 'IMPORT',
          entityType: 'Project',
          detailsJson: {
            source: 'typeform',
            formId: input.formId,
            roundId: input.roundId,
            imported: results.imported,
            skipped: results.skipped,
          },
          ipAddress: ctx.ip,
          userAgent: ctx.userAgent,
        },
      })

      return results
    }),
})
