import { toast } from 'sonner';
import { Dispatch, SetStateAction } from 'react';
import { onboardingService } from '@/services/onboarding.service';
import type { InterviewConfig } from './useInterviewConfigs';

interface UseApplicationDetailsFeedbackActionsParams {
  ktMatrixScores: Record<string, number>;
  setKtMatrixScores: Dispatch<SetStateAction<Record<string, number>>>;
  setKtMatrixSelectedValues: Dispatch<SetStateAction<Record<string, string>>>;
  ktMatrixRemarks: string;
  setKtMatrixRemarks: Dispatch<SetStateAction<string>>;
  ktMatrixRecommendation: string;
  setKtMatrixRecommendation: Dispatch<SetStateAction<string>>;
  selectedInterviewForFeedback: any;
  interviews: any[];
  setIsSubmittingKT: Dispatch<SetStateAction<boolean>>;
  setShowKTMatrixModal: Dispatch<SetStateAction<boolean>>;
  level2Feedback: any;
  setLevel2Feedback: Dispatch<SetStateAction<any>>;
  level2Recommendation: string;
  setLevel2Recommendation: Dispatch<SetStateAction<string>>;
  setIsSubmittingLevel2: Dispatch<SetStateAction<boolean>>;
  setShowLevel2FeedbackModal: Dispatch<SetStateAction<boolean>>;
  level3Feedback: any;
  setLevel3Feedback: Dispatch<SetStateAction<any>>;
  level3Recommendation: string;
  setLevel3Recommendation: Dispatch<SetStateAction<string>>;
  setIsSubmittingLevel3: Dispatch<SetStateAction<boolean>>;
  setShowLevel3FeedbackModal: Dispatch<SetStateAction<boolean>>;
  currentUser: any;
  fetchInterviews: () => Promise<void>;
  fetchApplication: (silent?: boolean) => Promise<void>;
  ktMatrixConfig: InterviewConfig | null;
  level2Config: InterviewConfig | null;
  level3Config: InterviewConfig | null;
}

const today = () => new Date().toISOString().split('T')[0];

const createInitialLevel2Feedback = (currentUser: any) => ({
  strategicVision: '',
  managementCapabilities: '',
  operationalUnderstanding: '',
  keyStrengths: '',
  areasOfConcern: '',
  additionalComments: '',
  overallScore: '',
  interviewerName: currentUser?.name || '',
  interviewDate: today(),
});

const createInitialLevel3Feedback = (currentUser: any) => ({
  strategicVision: '',
  managementCapabilities: '',
  operationalUnderstanding: '',
  brandAlignment: '',
  executiveSummary: '',
  keyStrengths: '',
  areasOfConcern: '',
  additionalComments: '',
  overallScore: '',
  interviewerName: currentUser?.name || '',
  interviewDate: today(),
});

export function useApplicationDetailsFeedbackActions({
  ktMatrixScores,
  setKtMatrixScores,
  setKtMatrixSelectedValues,
  ktMatrixRemarks,
  setKtMatrixRemarks,
  ktMatrixRecommendation,
  setKtMatrixRecommendation,
  selectedInterviewForFeedback,
  interviews,
  setIsSubmittingKT,
  setShowKTMatrixModal,
  level2Feedback,
  setLevel2Feedback,
  level2Recommendation,
  setLevel2Recommendation,
  setIsSubmittingLevel2,
  setShowLevel2FeedbackModal,
  level3Feedback,
  setLevel3Feedback,
  level3Recommendation,
  setLevel3Recommendation,
  setIsSubmittingLevel3,
  setShowLevel3FeedbackModal,
  currentUser,
  fetchInterviews,
  fetchApplication,
  ktMatrixConfig,
  level2Config,
  level3Config,
}: UseApplicationDetailsFeedbackActionsParams) {
  const mapRecommendationForFeedback = (value: string) => {
    if (value === 'Approve') return 'Recommended';
    if (value === 'Reject') return 'Not Recommended';
    return 'Hold';
  };

  const mapRecommendationForDecision = (value: string) => {
    if (value === 'Approve') return 'Approved';
    if (value === 'Reject') return 'Rejected';
    return null;
  };
  // Resolve active criteria/fields from config or fallback to hardcoded defaults
  const getKtCriteria = () => {
    if (ktMatrixConfig?.items && ktMatrixConfig.items.length > 0) {
      return ktMatrixConfig.items.map(item => ({
        name: item.label,
        weight: Number(item.weight) || 0,
        maxScore: Number(item.maxScore) || 10,
        options: (item.options || []).map(o => ({
          label: o.optionLabel,
          value: o.optionValue,
          score: Number(o.score) || 0,
        })),
      }));
    }
    return [];
  };

  const getLevel2Fields = () => {
    if (level2Config?.items && level2Config.items.length > 0) {
      return level2Config.items;
    }
    return [];
  };

  const getLevel3Fields = () => {
    if (level3Config?.items && level3Config.items.length > 0) {
      return level3Config.items;
    }
    return [];
  };

  const ktCriteria = getKtCriteria();
  const l2Fields = getLevel2Fields();
  const l3Fields = getLevel3Fields();

  const handleKTMatrixChange = (criterionName: string, value: string, score: number) => {
    setKtMatrixScores((prev) => ({ ...prev, [criterionName]: score }));
    setKtMatrixSelectedValues((prev) => ({ ...prev, [criterionName]: value }));
  };

  const calculateKTScore = () => {
    let totalWeightedScore = 0;
    ktCriteria.forEach((criterion: any) => {
      const score = ktMatrixScores[criterion.name || criterion.label] || 0;
      const maxScore = criterion.maxScore || 10;
      const weight = criterion.weight || 0;
      totalWeightedScore += (score / maxScore) * weight;
    });
    return totalWeightedScore.toFixed(2);
  };

  const handleSubmitKTMatrix = async () => {
    if (ktCriteria.length === 0) {
      toast.error('KT Matrix configuration is missing. Please configure it in Master > Interview Configurations.');
      return;
    }
    if (Object.keys(ktMatrixScores).length < ktCriteria.length) {
      toast.warning('Please fill all fields in the KT Matrix');
      return;
    }
    const interviewId = selectedInterviewForFeedback?.id || interviews.find((i) => i.status !== 'Completed')?.id || interviews[0]?.id;
    if (!interviewId) {
      toast.error('No active interview found to link this KT Matrix to.');
      return;
    }
    try {
      setIsSubmittingKT(true);
      const criteriaScores = ktCriteria.map((c: any) => ({
        criterionName: c.name || c.label,
        score: ktMatrixScores[c.name || c.label] || 0,
        maxScore: c.maxScore || 10,
        weightage: c.weight || 0,
      }));
      await onboardingService.submitKTMatrix({
        interviewId,
        criteriaScores,
        feedback: ktMatrixRemarks,
        recommendation: mapRecommendationForFeedback(ktMatrixRecommendation)
      });

      const decision = mapRecommendationForDecision(ktMatrixRecommendation);
      if (decision) {
        await onboardingService.updateInterviewDecision({
          interviewId,
          decision,
          remarks: ktMatrixRemarks || `Level 1 ${decision.toLowerCase()} via KT Matrix`
        });
      }

      toast.success(
        decision
          ? `KT Matrix submitted and interview ${decision.toLowerCase()}`
          : 'KT Matrix submitted and interview kept on hold'
      );
      setShowKTMatrixModal(false);
      setKtMatrixScores({});
      setKtMatrixSelectedValues({});
      setKtMatrixRemarks('');
      setKtMatrixRecommendation('Approve');
      await fetchInterviews();
      await fetchApplication();
    } catch {
      toast.error('Failed to submit KT Matrix');
    } finally {
      setIsSubmittingKT(false);
    }
  };

  const handleLevel2Change = (field: string, value: string) => {
    setLevel2Feedback((prev: any) => ({ ...prev, [field]: value }));
  };

  const handleSubmitLevel2Feedback = async () => {
    if (l2Fields.length === 0) {
      toast.error('Level 2 feedback configuration is missing. Please configure it in Master > Interview Configurations.');
      return;
    }
    if (!level2Feedback.overallScore) {
      toast.warning('Please provide an overall score.');
      return;
    }
    const interviewId = selectedInterviewForFeedback?.id || interviews.find((i) => i.status !== 'Completed' && i.level === 2)?.id;
    if (!interviewId) {
      toast.error('No active Level 2 interview found to link this feedback to.');
      return;
    }
    try {
      setIsSubmittingLevel2(true);
      const feedbackItems = l2Fields
        .map((f: any) => ({ type: f.label, comments: level2Feedback[f.itemKey] || '' }))
        .filter((item) => item.comments.trim() !== '');
      await onboardingService.submitLevel2Feedback({
        interviewId,
        overallScore: Number(level2Feedback.overallScore),
        feedbackItems,
        recommendation: mapRecommendationForFeedback(level2Recommendation)
      });

      const decision = mapRecommendationForDecision(level2Recommendation);
      const remarks = level2Feedback.additionalComments || 'Level 2 decision submitted via feedback modal';
      if (decision) {
        await onboardingService.updateInterviewDecision({ interviewId, decision, remarks });
      }

      toast.success(
        decision
          ? `Level 2 feedback submitted and interview ${decision.toLowerCase()}`
          : 'Level 2 feedback submitted and interview kept on hold'
      );
      setShowLevel2FeedbackModal(false);
      setLevel2Feedback(createInitialLevel2Feedback(currentUser));
      setLevel2Recommendation('Approve');
      await fetchInterviews();
      await fetchApplication();
    } catch {
      toast.error('Failed to submit Level 2 Feedback');
    } finally {
      setIsSubmittingLevel2(false);
    }
  };

  const handleLevel3Change = (field: string, value: string) => {
    setLevel3Feedback((prev: any) => ({ ...prev, [field]: value }));
  };

  const handleSubmitLevel3Feedback = async () => {
    if (l3Fields.length === 0) {
      toast.error('Level 3 feedback configuration is missing. Please configure it in Master > Interview Configurations.');
      return;
    }
    if (!level3Feedback.overallScore) {
      toast.warning('Please provide an overall score.');
      return;
    }
    const interviewId = selectedInterviewForFeedback?.id || interviews.find((i) => i.status !== 'Completed' && i.level === 3)?.id;
    if (!interviewId) {
      toast.error('No active Level 3 interview found to link this feedback to.');
      return;
    }
    try {
      setIsSubmittingLevel3(true);
      const feedbackItems = l3Fields
        .map((f: any) => ({ type: f.label, comments: level3Feedback[f.itemKey] || '' }))
        .filter((item) => item.comments.trim() !== '');
      await onboardingService.submitLevel2Feedback({
        interviewId,
        overallScore: Number(level3Feedback.overallScore),
        feedbackItems,
        recommendation: mapRecommendationForFeedback(level3Recommendation)
      });

      const decision = mapRecommendationForDecision(level3Recommendation);
      const remarks =
        level3Feedback.executiveSummary ||
        level3Feedback.additionalComments ||
        'Level 3 decision submitted via feedback modal';
      if (decision) {
        await onboardingService.updateInterviewDecision({ interviewId, decision, remarks });
      }

      toast.success(
        decision
          ? `Level 3 feedback submitted and interview ${decision.toLowerCase()}`
          : 'Level 3 feedback submitted and interview kept on hold'
      );
      setShowLevel3FeedbackModal(false);
      setLevel3Feedback(createInitialLevel3Feedback(currentUser));
      setLevel3Recommendation('Approve');
      await fetchInterviews();
      await fetchApplication();
    } catch {
      toast.error('Failed to submit Level 3 Feedback');
    } finally {
      setIsSubmittingLevel3(false);
    }
  };

  return {
    handleKTMatrixChange,
    calculateKTScore,
    handleSubmitKTMatrix,
    handleLevel2Change,
    handleSubmitLevel2Feedback,
    handleLevel3Change,
    handleSubmitLevel3Feedback,
    ktCriteria,
    l2Fields,
    l3Fields,
  };
}

