import { ApiProperty } from '@nestjs/swagger';
import { 
  IsInt, 
  IsNotEmpty, 
  IsOptional, 
  IsArray, 
  IsString, 
  IsObject, 
  ValidateNested,
  IsEnum,
  ValidateIf,
  IsBoolean
} from 'class-validator';
import { Type } from 'class-transformer';
import { QuestionType } from 'src/common/enum/question-type.enum';
import { AnswerType } from 'src/common/enum/answer-type.enum';

/**
 * DTO for overriding section properties when cloning
 */
export class SectionOverrideDto {
  @ApiProperty({ 
    description: 'Override section name', 
    example: 'Personal Information (Updated)',
    required: false 
  })
  @IsOptional()
  @IsString()
  sectionName?: string;

  @ApiProperty({ 
    description: 'Override section description', 
    example: 'Modified description',
    required: false 
  })
  @IsOptional()
  @IsString()
  sectionDescription?: string;


  @ApiProperty({ 
    description: 'Override visibility', 
    example: true,
    required: false 
  })
  @IsOptional()
  isVisible?: boolean;

  @ApiProperty({ 
    description: 'Override conditional configuration', 
    example: { showIf: { questionId: 5, value: 'yes' } },
    required: false 
  })
  @IsOptional()
  @IsObject()
  conditionalConfig?: Record<string, any>;
}

/**
 * DTO for overriding question properties when cloning
 */
export class QuestionOverrideDto {
  @ApiProperty({ 
    description: 'Override question label/text', 
    example: 'What is your full name?',
    required: false 
  })
  @IsOptional()
  @IsString()
  label?: string;

  @ApiProperty({ 
    description: 'Override placeholder text', 
    example: 'Enter your name here',
    required: false 
  })
  @IsOptional()
  @IsString()
  placeholder?: string;

  @ApiProperty({ 
    description: 'Override help text', 
    example: 'Please enter your name as shown on official documents',
    required: false 
  })
  @IsOptional()
  @IsString()
  helpText?: string;



  @ApiProperty({ 
    description: 'Override visibility', 
    example: true,
    required: false 
  })
  @IsOptional()
  isVisible?: boolean;

  @ApiProperty({ 
    description: 'Override question configuration (validation rules, etc.)', 
    example: { isRequired: true, minCharacter: 5, maxCharacters: 100 },
    required: false 
  })
  @IsOptional()
  @IsObject()
  config?: Record<string, any>;

  @ApiProperty({
    description: 'Override conditional configuration',
    required: false,
    type: Object,
  })
  @IsOptional()
  @IsObject()
  conditionalConfig?: Record<string, any>;

  @ApiProperty({ 
    description: 'Override option configuration for dropdown/radio/checkbox questions', 
    example: [{ value: 'yes', label: 'Yes' }, { value: 'no', label: 'No' }],
    required: false 
  })
  @IsOptional()
  @IsArray()
  optionConfig?: Record<string, any>[];

  @ApiProperty({ 
    description: 'Override required status', 
    example: true,
    required: false 
  })
  @IsOptional()
  isRequired?: boolean;
}

/**
 * DTO for question input - can be clone from master or create new
 * 
 * USAGE:
 * - Option 1: Clone from master question (provide masterQuestionId)
 * - Option 2: Create new question (provide label + type + answerType)
 * 
 * IMPORTANT:
 * - Must specify EXACTLY ONE of the two options above
 * - For dropdown/radio/checkbox/multiselect types: optionConfig is REQUIRED
 * - override can be used with Option 1 to customize cloned questions
 * 
 * @example Clone from master with override
 * {
 *   "masterQuestionId": 100,
 *   "override": {
 *     "label": "Full Name (As per ID)",
 *     "config": { "isRequired": true, "maxCharacters": 100 }
 *   }
 * }
 * 
 * @example Create new question
 * {
 *   "label": "Emergency Contact Phone",
 *   "type": "tel",
 *   "answerType": "string",
 *   "config": { "isRequired": true },
 *   "placeholder": "+91 XXXXX XXXXX",
 *   "displayOrder": 1
 * }
 * 
 * @example Create dropdown question
 * {
 *   "label": "Dietary Preference",
 *   "type": "dropdown",
 *   "answerType": "string",
 *   "optionConfig": [
 *     { "value": "veg", "label": "Vegetarian" },
 *     { "value": "nonveg", "label": "Non-Vegetarian" },
 *     { "value": "vegan", "label": "Vegan" }
 *   ]
 * }
 */
export class QuestionInputDto {
  // Option 1: Clone from master question
  @ApiProperty({ 
    description: 'Master question ID to clone from (mutually exclusive with label+type)', 
    example: 100,
    required: false 
  })
  @IsOptional()
  @IsInt()
  masterQuestionId?: number;

  // Option 2: Create new question
  @ApiProperty({ 
    description: 'Question label/text (required if creating new question)', 
    example: 'What is your email address?',
    required: false 
  })
  @IsOptional()
  @IsString()
  label?: string;

  @ApiProperty({ 
    description: 'Question type (required if creating new question)', 
    example: 'text',
    enum: QuestionType,
    required: false 
  })
  @IsOptional()
  @IsEnum(QuestionType)
  type?: QuestionType;

  @ApiProperty({ 
    description: 'Answer type (required if creating new question)', 
    example: 'string',
    enum: AnswerType,
    required: false 
  })
  @IsOptional()
  @IsEnum(AnswerType)
  answerType?: AnswerType;

  @ApiProperty({ 
    description: 'Question configuration', 
    example: { isRequired: true, maxCharacters: 100 },
    required: false 
  })
  @IsOptional()
  @IsObject()
  config?: Record<string, any>;

  @ApiProperty({ 
    description: 'Placeholder text', 
    example: 'Enter your email',
    required: false 
  })
  @IsOptional()
  @IsString()
  placeholder?: string;

  @ApiProperty({ 
    description: 'Help text', 
    example: 'We will use this email to contact you',
    required: false 
  })
  @IsOptional()
  @IsString()
  helpText?: string;

  @ApiProperty({ 
    description: 'Display order within section', 
    example: 1,
    required: false 
  })
  @IsOptional()
  @IsInt()
  displayOrder?: number;

  @ApiProperty({ 
    description: 'Option configuration for dropdown/radio/checkbox questions', 
    example: [{ value: 'yes', label: 'Yes' }, { value: 'no', label: 'No' }],
    required: false 
  })
  @IsOptional()
  @IsArray()
  optionConfig?: Record<string, any>[];

  @ApiProperty({ 
    description: 'Overrides to apply when cloning from master', 
    type: QuestionOverrideDto,
    required: false 
  })
  @IsOptional()
  @ValidateNested()
  @Type(() => QuestionOverrideDto)
  override?: QuestionOverrideDto;
}

/**
 * DTO for section input - can be clone from master or create new
 * 
 * USAGE:
 * - Option 1: Clone from master section (provide masterFormSectionId)
 * - Option 2: Create new section (provide sectionName + sectionKey)
 * 
 * IMPORTANT:
 * - Must specify EXACTLY ONE of the two options above
 * - Questions array is REQUIRED and must not be empty
 * 
 * SUBSECTIONS (parentSectionId):
 * - Any section can have unlimited subsections
 * - Nesting depth is controlled by MAX_SECTION_NESTING_DEPTH constant
 * 
 * @example Clone from master section with override
 * {
 *   "masterFormSectionId": 10,
 *   "sectionOverride": {
 *     "sectionName": "Personal Details (Updated)",
 *     "displayOrder": 1
 *   },
 *   "questions": [
 *     {
 *       "masterQuestionId": 100,
 *       "override": { "label": "Full Name" }
 *     }
 *   ]
 * }
 * 
 * @example Create new custom section
 * {
 *   "sectionName": "Emergency Contact",
 *   "sectionKey": "EMERGENCY_CONTACT",
 *   "sectionDescription": "Please provide emergency contact details",
 *   "displayOrder": 2,
 *   "questions": [
 *     {
 *       "label": "Contact Name",
 *       "type": "text",
 *       "answerType": "string",
 *       "config": { "isRequired": true, "maxCharacters": 100 }
 *     },
 *     {
 *       "label": "Relationship",
 *       "type": "dropdown",
 *       "answerType": "string",
 *       "optionConfig": [
 *         { "value": "parent", "label": "Parent" },
 *         { "value": "spouse", "label": "Spouse" }
 *       ]
 *     }
 *   ]
 * }
 * 
 * @example Create nested subsections (hierarchical structure) - NEW inside NEW
 * {
 *   "sectionName": "Main Section",
 *   "sectionKey": "MAIN_SECTION",
 *   "displayOrder": 1,
 *   "questions": [
 *     {
 *       "label": "Main Question",
 *       "type": "text",
 *       "answerType": "string",
 *       "config": { "isRequired": true }
 *     }
 *   ],
 *   "subsections": [
 *     {
 *       "sectionName": "Child Subsection",
 *       "sectionKey": "CHILD_SUBSECTION",
 *       "displayOrder": 1,
 *       "questions": [
 *         {
 *           "label": "Child Question",
 *           "type": "text",
 *           "answerType": "string",
 *           "config": { "isRequired": true }
 *         }
 *       ],
 *       "subsections": [
 *         {
 *           "sectionName": "Nested Subsection",
 *           "sectionKey": "NESTED_SUBSECTION",
 *           "questions": [...]
 *         }
 *       ]
 *     }
 *   ]
 * }
 * 
 * @example Add subsections to EXISTING section
 * {
 *   "templateFormSectionId": 33,  // Existing section ID
 *   "subsections": [
 *     {
 *       "sectionName": "New Child Under Existing",
 *       "sectionKey": "NEW_CHILD",
 *       "questions": [...]
 *     }
 *   ]
 * }
 * 
 * @example NEW section with EXISTING section as subsection
 * {
 *   "sectionName": "New Parent Section",
 *   "sectionKey": "NEW_PARENT",
 *   "questions": [...],
 *   "subsections": [
 *     {
 *       "templateFormSectionId": 33  // Reference existing section as child
 *     },
 *     {
 *       "sectionName": "Another New Child",
 *       "sectionKey": "NEW_CHILD_2",
 *       "questions": [...]
 *     }
 *   ]
 * }
 * 
 * @example EXISTING section with EXISTING section as subsection
 * {
 *   "templateFormSectionId": 33,  // Existing parent
 *   "subsections": [
 *     {
 *       "templateFormSectionId": 34  // Existing subsection to link
 *     }
 *   ]
 * }
 */
export class SectionInputDto {
  // Option 1: Clone from master section
  @ApiProperty({ 
    description: 'Master form section ID to clone from (mutually exclusive with other options)', 
    example: 10,
    required: false 
  })
  @IsOptional()
  @IsInt()
  masterFormSectionId?: number;

  // Option 2: Create new section
  @ApiProperty({ 
    description: 'Section name (required if creating new section)', 
    example: 'Personal Information',
    required: false 
  })
  @IsOptional()
  @IsString()
  sectionName?: string;

  @ApiProperty({ 
    description: 'Section key (required if creating new section)', 
    example: 'PERSONAL_INFO',
    required: false 
  })
  @IsOptional()
  @IsString()
  sectionKey?: string;

  // Option 3: Reference existing template section (to add subsections to it or use as subsection)
  @ApiProperty({ 
    description: 'Existing template form section ID (use to add subsections to existing section or reference as subsection)', 
    example: 33,
    required: false 
  })
  @IsOptional()
  @IsInt()
  templateFormSectionId?: number;

  @ApiProperty({ 
    description: 'Section description', 
    example: 'Please provide your personal details',
    required: false 
  })
  @IsOptional()
  @IsString()
  sectionDescription?: string;

  @ApiProperty({ 
    description: 'Display order', 
    example: 1,
    required: false 
  })
  @IsOptional()
  @IsInt()
  displayOrder?: number;

  @ApiProperty({ 
    description: 'Parent section ID for nested sections (use this for existing sections)', 
    example: 5,
    required: false 
  })
  @IsOptional()
  @IsInt()
  parentSectionId?: number;

  @ApiProperty({ 
    description: 'Conditional configuration', 
    example: { showIf: { questionId: 10, value: 'yes' } },
    required: false 
  })
  @IsOptional()
  @IsObject()
  conditionalConfig?: Record<string, any>;

  @ApiProperty({ 
    description: 'Section override properties when cloning from master', 
    type: SectionOverrideDto,
    required: false 
  })
  @IsOptional()
  @ValidateNested()
  @Type(() => SectionOverrideDto)
  sectionOverride?: SectionOverrideDto;

  @ApiProperty({ 
    description: 'Questions to include in this section (REQUIRED for new/cloned sections, OPTIONAL for existing sections)', 
    type: [QuestionInputDto],
    isArray: true,
    required: false,
    example: [
      {
        masterQuestionId: 100,
        override: {
          label: 'Full Name',
          config: { isRequired: true }
        }
      },
      {
        label: 'Email Address',
        type: 'email',
        answerType: 'string',
        config: { isRequired: true },
        placeholder: 'your@email.com'
      }
    ]
  })
  @IsOptional()
  @IsArray()
  @ValidateNested({ each: true })
  @Type(() => QuestionInputDto)
  questions?: QuestionInputDto[];

  @ApiProperty({ 
    description: 'Nested subsections (optional) - allows creating hierarchical section structures', 
    type: [SectionInputDto],
    isArray: true,
    required: false,
    example: [
      {
        sectionName: 'Child Section',
        sectionKey: 'CHILD_SECTION',
        questions: [
          {
            label: 'Child Question',
            type: 'text',
            answerType: 'string'
          }
        ]
      }
    ]
  })
  @IsOptional()
  @IsArray()
  @ValidateNested({ each: true })
  @Type(() => SectionInputDto)
  subsections?: SectionInputDto[];
}

/**
 * Main DTO for template form builder API (Master → Template)
 * 
 * This unified endpoint supports:
 * - **NEW: Direct master cloning** - Clone all sections/questions from a master form at once
 * - Cloning sections from master with optional overrides
 * - Creating brand new custom sections
 * - Cloning questions from master with optional overrides
 * - Creating brand new custom questions
 * - Creating nested subsections (depth controlled by MAX_SECTION_NESTING_DEPTH constant)
 * - Mixing cloned and custom content in same request
 * 
 * DIRECT MASTER CLONING:
 * - Provide masterFormId and set cloneFromMaster: true
 * - This will automatically clone ALL sections and questions from the master form
 * - Optional: sections array can be empty when using direct master cloning
 * - If both master cloning and sections array are provided, both will be processed
 * 
 * @example Direct master cloning
 * {
 *   "programTemplateId": 5,
 *   "masterFormId": 2,
 *   "cloneFromMaster": true,
 *   "createdBy": 1
 * }
 * 
 * @example Master cloning + custom sections
 * {
 *   "programTemplateId": 5,
 *   "masterFormId": 2,
 *   "cloneFromMaster": true,
 *   "sections": [
 *     {
 *       "sectionName": "Additional Custom Section",
 *       "sectionKey": "CUSTOM_SECTION",
 *       "questions": [...]
 *     }
 *   ],
 *   "createdBy": 1
 * }
 * 
 * @example Manual sections only (existing behavior)
 * {
 *   "programTemplateId": 5,
 *   "sections": [
 *     {
 *       "masterFormSectionId": 10,
 *       "sectionOverride": {
 *         "sectionName": "Personal Information",
 *         "displayOrder": 1
 *       },
 *       "questions": [
 *         {
 *           "masterQuestionId": 100,
 *           "override": {
 *             "label": "Full Name",
 *             "config": { "isRequired": true }
 *           }
 *         }
 *       ]
 *     },
 *     {
 *       "sectionName": "Emergency Contact",
 *       "sectionKey": "EMERGENCY_CONTACT",
 *       "displayOrder": 2,
 *       "questions": [
 *         {
 *           "label": "Contact Name",
 *           "type": "text",
 *           "answerType": "string",
 *           "config": { "isRequired": true, "maxCharacters": 100 }
 *         }
 *       ]
 *     }
 *   ],
 *   "createdBy": 1
 * }
 */
export class TemplateFormBuilderDto {
  @ApiProperty({ 
    description: 'Program template ID to build form for (can be provided in request body or route parameter)', 
    example: 5,
    required: false
  })
  @IsOptional()
  @IsInt()
  programTemplateId?: number;

  @ApiProperty({ 
    description: 'Master form ID to clone all sections and questions from (use with cloneFromMaster: true)', 
    example: 2,
    required: false 
  })
  @IsOptional()
  @IsInt()
  masterFormId?: number;

  @ApiProperty({ 
    description: 'Enable direct cloning from master form (clones all sections and questions from masterFormId)', 
    example: true,
    required: false,
    default: false
  })
  @IsOptional()
  @IsBoolean()
  cloneFromMaster?: boolean;

  @ApiProperty({ 
    description: 'Sections to create/clone (optional if using direct master cloning, otherwise REQUIRED)', 
    type: [SectionInputDto],
    isArray: true,
    example: [
      {
        masterFormSectionId: 10,
        sectionOverride: {
          sectionName: 'Personal Details (Updated)',
          displayOrder: 1
        },
        questions: [
          {
            masterQuestionId: 100,
            override: {
              label: 'Full Name',
              config: { isRequired: true }
            }
          }
        ]
      },
      {
        sectionName: 'Emergency Contact',
        sectionKey: 'EMERGENCY_CONTACT',
        displayOrder: 2,
        questions: [
          {
            label: 'Contact Name',
            type: 'text',
            answerType: 'string',
            config: { isRequired: true }
          }
        ]
      }
    ]
  })
  @IsOptional()
  @IsArray()
  @ValidateNested({ each: true })
  @Type(() => SectionInputDto)
  sections?: SectionInputDto[];

  @ApiProperty({ 
    description: 'User ID performing the operation', 
    example: 1 
  })
  @IsInt()
  @IsNotEmpty()
  createdBy: number;
}

/**
 * Response DTO for template form builder
 */
export class TemplateFormBuilderResponseDto {
  @ApiProperty({ 
    description: 'Success status',
    example: true
  })
  success: boolean;

  @ApiProperty({ 
    description: 'Response message',
    example: 'Template form built successfully'
  })
  message: string;

  @ApiProperty({ 
    description: 'Created template form sections with questions',
    example: {
      templateFormSections: [
        {
          id: 31,
          name: 'Personal Information',
          sectionKey: 'PERSONAL_INFO',
          displayOrder: 1,
          programTemplateId: 5,
          createdAt: '2026-03-18T10:30:00Z'
        },
        {
          id: 32,
          name: 'Emergency Contact',
          sectionKey: 'EMERGENCY_CONTACT',
          displayOrder: 2,
          programTemplateId: 5,
          createdAt: '2026-03-18T10:30:00Z'
        }
      ],
      totalSectionsCreated: 2,
      totalQuestionsCreated: 5
    }
  })
  data: {
    templateFormSections: any[];
    totalSectionsCreated: number;
    totalQuestionsCreated: number;
  };
}
