
import { DemographicInfoDto, QuestionResponseDto } from "../dto/report.dto";
import NepaliDate from 'nepali-datetime'


/**
 * Maps frontend form responses to the financial fraud form data structure
 */
export function mapToFinancialFraudForm(responses: QuestionResponseDto[], demographicInfo: DemographicInfoDto): FinancialFraudFormData {
  const getAnswerByQuestionId = (id: string): string => {
    const response = responses.find(r => r.questionId === id);
    return response ? (Array.isArray(response.answer) ? response.answer.join(', ') : response.answer) : '';
  }

  // Format Nepali date for complaint date
  const currentDate = new NepaliDate();
  const formattedDate = `${currentDate.getDate()}/${currentDate.getMonth() + 1}/${currentDate.getYear().toString().slice(-2)}`;
  // Get incident date
  const incidentDate = getAnswerByQuestionId('1'); // "When did you first notice suspicious activity?"
  // const parsedIncidentDate = parseDateString(incidentDate);

  // Get social media platform
  let socialMediaPlatform: "FB/Messenger" | "Insta" | "WhatsApp" | "Tiktok" | "Other" = "Other";
  const platform = getAnswerByQuestionId('100'); // Updated ID: "What platform was the fraud committed on?"

  if (platform.toLowerCase().includes('facebook') || platform.toLowerCase().includes('messenger')) {
    socialMediaPlatform = "FB/Messenger";
  } else if (platform.toLowerCase().includes('insta')) {
    socialMediaPlatform = "Insta";
  } else if (platform.toLowerCase().includes('whatsapp')) {
    socialMediaPlatform = "WhatsApp";
  } else if (platform.toLowerCase().includes('tiktok')) {
    socialMediaPlatform = "Tiktok";
  }

  // Check which documents are attached
  const documentsAnswer = getAnswerByQuestionId('110'); // Updated ID: "Please attach the following documents:"

  return {
    // Complaint date details
    complaintDate: formattedDate,
    complaintDay: currentDate.getDate().toString(),
    complaintMonth: (currentDate.getMonth()).toString(),
    complaintYear: (currentDate.getYear()).toString(),

    // Complainant details
    complainantName: getAnswerByQuestionId('102'), // Updated ID: "Your full name:"
    complainantDateOfBirth: getAnswerByQuestionId('103'), // Updated ID: "Date of birth:"
    complainantAddress: getAnswerByQuestionId('104'), // Updated ID: "Address:"
    complainantIdNumber: getAnswerByQuestionId('105'), // Updated ID: "Personal ID number:"
    complainantContactNumber: getAnswerByQuestionId('106'), // Updated ID: "Your contact number:"
    complainantGuardianContactNumber: getAnswerByQuestionId('107'), // Updated ID: "Guardian's contact number:"

    // Case details
    originalID_URL: getAnswerByQuestionId('108'), // Updated ID: "Your original ID/URL:"
    fraudsterID_URL: getAnswerByQuestionId('109'), // Updated ID: "Fraudster's ID/URL:"
    socialMediaPlatform: socialMediaPlatform,
    incidentDescription: getAnswerByQuestionId('101'), // Updated ID: "Please describe the fraud incident briefly:"

    // Attached documents
    hasScreenshots: documentsAnswer.toLowerCase().includes('screenshot'),
    hasCitizenshipCopy: documentsAnswer.toLowerCase().includes('citizenship'),
    hasPassport: documentsAnswer.toLowerCase().includes('passport'),
    hasNationalIDCard: documentsAnswer.toLowerCase().includes('national id'),
    hasEmployeeOrStudentID: documentsAnswer.toLowerCase().includes('student') || documentsAnswer.toLowerCase().includes('employee'),
    otherDocument: documentsAnswer.toLowerCase().includes('other') ? 'Other documents provided' : ''
  };
}

/**
 * Maps frontend form responses to the fake or hacked form data structure
 */
export function mapToFakeOrHackedForm(responses: QuestionResponseDto[], demographicInfo: DemographicInfoDto): FakeOrHackedFormData {

  // Get current date for the complaint date
  const today = new Date();
  const currentYear = today.getFullYear().toString();
  const currentMonth = (today.getMonth() + 1).toString().padStart(2, '0');
  const currentDay = today.getDate().toString().padStart(2, '0');

  // Helper function to find answer by question ID
  const getAnswer = (questionId: number): string => {
    const response = responses.find(r => r.questionId === questionId.toString());
    return response ? (Array.isArray(response.answer) ? response.answer.join(', ') : response.answer) : '';
  };

  // Helper function to check if an answer contains a specific option
  const hasOption = (questionId: number, option: string): boolean => {
    const answer = getAnswer(questionId);
    return answer.toLowerCase().includes(option.toLowerCase());
  };

  // Process social media platform (from question 200)
  const socialMediaPlatform = getAnswer(200);

  // Process incident type (from question 201)
  const incidentType = {
    hackedID: hasOption(201, 'hacked'),
    fakeID: hasOption(201, 'fake')
  };

  // Process additional details (from question 202)
  const additionalDetails = {
    mediaContent: hasOption(202, 'video') || hasOption(202, 'photo') ||
      hasOption(202, 'audio') || hasOption(202, 'post'),
    financialTransaction: hasOption(202, 'financial'),
    other: hasOption(202, 'other') ? getAnswer(202) : ""
  };

  // Process documents (from question 203)
  const documents = {
    citizenshipCopy: hasOption(203, 'citizenship'),
    passport: hasOption(203, 'passport'),
    nationalIDCard: hasOption(203, 'national id'),
    employeeOrStudentID: hasOption(203, 'employee') || hasOption(203, 'student'),
    screenshots: true, // Assuming screenshots are always attached
    otherDocument: hasOption(203, 'other') ? getAnswer(203) : ""
  };

  // Process language (from question 204)
  const language = {
    english: hasOption(204, 'english'),
    nepali: hasOption(204, 'nepali'),
    other: ""
  };

  // Personal information
  const fullName = getAnswer(210);
  const dateOfBirth = getAnswer(211);
  const address = getAnswer(212);
  const idNumber = getAnswer(213);
  const contactNumber = getAnswer(214);
  const guardianContactNumber = getAnswer(215);

  // Account details
  const fakeOrHackedURL = getAnswer(216);
  const profileFullName = getAnswer(217);
  const currentProfileURL = getAnswer(218);
  const idCreationDate = getAnswer(219);
  const adminDetails = getAnswer(220);
  const hackDate = getAnswer(205);
  const previousPhoneNumber = getAnswer(206);
  const previousEmail = getAnswer(207);
  const deviceDetails = getAnswer(208);
  const unusedEmail = getAnswer(209);

  // Determine if date is AD or BS (this is a simplistic check, enhance as needed)
  const isDateBS = idCreationDate.includes('/') &&
    parseInt(idCreationDate.split('/')[0]) > 2000;

  return {
    complaintDate: {
      year: currentYear,
      month: currentMonth,
      day: currentDay
    },
    socialMediaPlatform: socialMediaPlatform,
    incidentType: incidentType,
    additionalDetails: additionalDetails,
    attachedDocuments: documents,
    complainant: {
      name: fullName || "",
      dateOfBirth: dateOfBirth || "",
      address: address || "",
      idNumber: idNumber || "",
      contactNumber: contactNumber || "",
      guardianContactNumber: guardianContactNumber || ""
    },
    adminDetails: adminDetails || "",
    accountDetails: {
      fakeOrHackedURL: fakeOrHackedURL || "",
      profileFullName: profileFullName || "",
      languageUsed: language,
      hackDate: hackDate || "",
      previousPhoneNumber: previousPhoneNumber || "",
      previousEmail: previousEmail || "",
      deviceDetails: deviceDetails || "",
      idCreationDate: {
        isAD: !isDateBS,
        isBS: isDateBS,
        date: idCreationDate || ""
      },
      currentProfileURL: currentProfileURL || "",
      unusedEmail: unusedEmail || ""
    }
  };
}

/**
 * Maps frontend form responses to the Karbahi (other) form data structure
 */
export function mapToKarbahiForm(responses: QuestionResponseDto[], demographicInfo: DemographicInfoDto): KarbahiFormData {
  // Helper function to find answer by question ID
  const getAnswerByQuestionId = (id: string): string => {
    const response = responses.find(r => r.questionId === id);
    return response ? (Array.isArray(response.answer) ? response.answer.join(', ') : response.answer) : '';
  };

  // Format current date for complaint date
  const currentDate = new Date();

  // Get incident type directly from the form response
  const incidentType = getAnswerByQuestionId('301'); // "What type of incident occurred?"
  const platform = getAnswerByQuestionId('302'); // "Which platform was the incident conducted through?"
  const documentsAnswer = getAnswerByQuestionId('306'); // "Which documents are you attaching?"

  return {
    complaintDate: {
      year: (currentDate.getFullYear() + 57).toString(), // Converting to BS year
      month: (currentDate.getMonth() + 1).toString().padStart(2, '0'),
      day: currentDate.getDate().toString().padStart(2, '0')
    },
    subject: getAnswerByQuestionId('299'),
    caseDetails: {
      originalID_URL: getAnswerByQuestionId('300'), // "Original ID/URL of the victim"
      incidentType: {
        mediaContent: incidentType.includes('Media Content'),
        financialTransaction: incidentType.includes('Financial Transaction'),
        unauthorizedAccess: incidentType.includes('Unauthorized Access')
      },
      socialMediaPlatform: platform, // "Which platform was the incident conducted through?"
      fraudsterID_URL: getAnswerByQuestionId('303'), // "ID/URL of the person or organization responsible for the incident"
      incidentDescription: getAnswerByQuestionId('304'), // "Brief description of the incident"
      suspectDetails: getAnswerByQuestionId('305'), // "Information of suspect (name, address, phone, email, etc.)"
      attachedDocuments: {
        screenshots: documentsAnswer.includes('Screenshots'),
        citizenshipCopy: documentsAnswer.includes('Citizenship'),
        passport: documentsAnswer.includes('Passport'),
        nationalIDCard: documentsAnswer.includes('National ID'),
        employeeOrStudentID: documentsAnswer.includes('Employee/Student ID'),
        otherDocument: documentsAnswer.includes('Other') ? 'Other documents provided' : ''
      }
    },
    complainant: {
      name: getAnswerByQuestionId('308'), // "Your Full Name"
      dateOfBirth: getAnswerByQuestionId('309'), // "Your Birth Date"
      address: getAnswerByQuestionId('310'), // "Your Address"
      idNumber: getAnswerByQuestionId('311'), // "Your ID Number"
      contactNumber: getAnswerByQuestionId('312'), // "Your Contact Number"
      guardianContactNumber: getAnswerByQuestionId('313'), // "Guardian's Contact Number (if applicable)"
    }
  };
}