import React, { useState, useEffect } from 'react';
import { Save, Download } from 'lucide-react';
import { cn } from '../utils/cn';

interface CIMReviewData {
  // Deal Overview
  dealOverview: {
    targetCompanyName: string;
    industrySector: string;
    geography: string;
    dealSource: string;
    transactionType: string;
    dateCIMReceived: string;
    dateReviewed: string;
    reviewers: string;
    cimPageCount: string;
    statedReasonForSale: string;
    employeeCount: string;
  };

  // Business Description
  businessDescription: {
    coreOperationsSummary: string;
    keyProductsServices: string;
    uniqueValueProposition: string;
    customerBaseOverview: {
      keyCustomerSegments: string;
      customerConcentrationRisk: string;
      typicalContractLength: string;
    };
    keySupplierOverview: {
      dependenceConcentrationRisk: string;
    };
  };

  // Market & Industry Analysis
  marketIndustryAnalysis: {
    estimatedMarketSize: string;
    estimatedMarketGrowthRate: string;
    keyIndustryTrends: string;
    competitiveLandscape: {
      keyCompetitors: string;
      targetMarketPosition: string;
      basisOfCompetition: string;
    };
    barriersToEntry: string;
  };

  // Financial Summary
  financialSummary: {
    financials: {
      fy3: { revenue: string; revenueGrowth: string; grossProfit: string; grossMargin: string; ebitda: string; ebitdaMargin: string };
      fy2: { revenue: string; revenueGrowth: string; grossProfit: string; grossMargin: string; ebitda: string; ebitdaMargin: string };
      fy1: { revenue: string; revenueGrowth: string; grossProfit: string; grossMargin: string; ebitda: string; ebitdaMargin: string };
      ltm: { revenue: string; revenueGrowth: string; grossProfit: string; grossMargin: string; ebitda: string; ebitdaMargin: string };
    };
    qualityOfEarnings: string;
    revenueGrowthDrivers: string;
    marginStabilityAnalysis: string;
    capitalExpenditures: string;
    workingCapitalIntensity: string;
    freeCashFlowQuality: string;
  };

  // Management Team Overview
  managementTeamOverview: {
    keyLeaders: string;
    managementQualityAssessment: string;
    postTransactionIntentions: string;
    organizationalStructure: string;
  };

  // Preliminary Investment Thesis
  preliminaryInvestmentThesis: {
    keyAttractions: string;
    potentialRisks: string;
    valueCreationLevers: string;
    alignmentWithFundStrategy: string;
  };

  // Key Questions & Next Steps
  keyQuestionsNextSteps: {
    criticalQuestions: string;
    missingInformation: string;
    preliminaryRecommendation: string;
    rationaleForRecommendation: string;
    proposedNextSteps: string;
  };
}

interface CIMReviewTemplateProps {
  initialData?: Partial<CIMReviewData>;
  cimReviewData?: any;
  onSave?: (data: CIMReviewData) => void;
  onExport?: (data: CIMReviewData) => void;
  readOnly?: boolean;
}

const CIMReviewTemplate: React.FC<CIMReviewTemplateProps> = ({
  initialData = {},
  cimReviewData,
  onSave,
  onExport,
  readOnly = false,
}) => {
  const [data, setData] = useState<CIMReviewData>({
    // Deal Overview
    dealOverview: initialData.dealOverview || {
      targetCompanyName: '',
      industrySector: '',
      geography: '',
      dealSource: '',
      transactionType: '',
      dateCIMReceived: '',
      dateReviewed: '',
      reviewers: '',
      cimPageCount: '',
      statedReasonForSale: '',
      employeeCount: '',
    },

    // Business Description
    businessDescription: initialData.businessDescription || {
      coreOperationsSummary: '',
      keyProductsServices: '',
      uniqueValueProposition: '',
      customerBaseOverview: {
        keyCustomerSegments: '',
        customerConcentrationRisk: '',
        typicalContractLength: '',
      },
      keySupplierOverview: {
        dependenceConcentrationRisk: '',
      },
    },

    // Market & Industry Analysis
    marketIndustryAnalysis: initialData.marketIndustryAnalysis || {
      estimatedMarketSize: '',
      estimatedMarketGrowthRate: '',
      keyIndustryTrends: '',
      competitiveLandscape: {
        keyCompetitors: '',
        targetMarketPosition: '',
        basisOfCompetition: '',
      },
      barriersToEntry: '',
    },

    // Financial Summary
    financialSummary: initialData.financialSummary || {
      financials: {
        fy3: { revenue: '', revenueGrowth: '', grossProfit: '', grossMargin: '', ebitda: '', ebitdaMargin: '' },
        fy2: { revenue: '', revenueGrowth: '', grossProfit: '', grossMargin: '', ebitda: '', ebitdaMargin: '' },
        fy1: { revenue: '', revenueGrowth: '', grossProfit: '', grossMargin: '', ebitda: '', ebitdaMargin: '' },
        ltm: { revenue: '', revenueGrowth: '', grossProfit: '', grossMargin: '', ebitda: '', ebitdaMargin: '' },
      },
      qualityOfEarnings: '',
      revenueGrowthDrivers: '',
      marginStabilityAnalysis: '',
      capitalExpenditures: '',
      workingCapitalIntensity: '',
      freeCashFlowQuality: '',
    },

    // Management Team Overview
    managementTeamOverview: initialData.managementTeamOverview || {
      keyLeaders: '',
      managementQualityAssessment: '',
      postTransactionIntentions: '',
      organizationalStructure: '',
    },

    // Preliminary Investment Thesis
    preliminaryInvestmentThesis: initialData.preliminaryInvestmentThesis || {
      keyAttractions: '',
      potentialRisks: '',
      valueCreationLevers: '',
      alignmentWithFundStrategy: '',
    },

    // Key Questions & Next Steps
    keyQuestionsNextSteps: initialData.keyQuestionsNextSteps || {
      criticalQuestions: '',
      missingInformation: '',
      preliminaryRecommendation: '',
      rationaleForRecommendation: '',
      proposedNextSteps: '',
    },
  });

  const [activeSection, setActiveSection] = useState<string>('deal-overview');

  // Merge cimReviewData with existing data when it changes
  useEffect(() => {
    if (cimReviewData && Object.keys(cimReviewData).length > 0) {
      setData(prev => ({
        ...prev,
        ...cimReviewData
      }));
    }
  }, [cimReviewData]);

  

  const updateFinancials = (period: keyof CIMReviewData['financialSummary']['financials'], field: string, value: string) => {
    setData(prev => ({
      ...prev,
      financialSummary: {
        ...prev.financialSummary,
        financials: {
          ...prev.financialSummary.financials,
          [period]: {
            ...prev.financialSummary.financials[period],
            [field]: value,
          },
        },
      },
    }));
  };

  const handleSave = () => {
    onSave?.(data);
  };

  const handleExport = () => {
    onExport?.(data);
  };

  const sections = [
    { id: 'deal-overview', title: 'Deal Overview', icon: '📋' },
    { id: 'business-description', title: 'Business Description', icon: '🏢' },
    { id: 'market-analysis', title: 'Market & Industry Analysis', icon: '📊' },
    { id: 'financial-summary', title: 'Financial Summary', icon: '💰' },
    { id: 'management-team', title: 'Management Team Overview', icon: '👥' },
    { id: 'investment-thesis', title: 'Preliminary Investment Thesis', icon: '🎯' },
    { id: 'next-steps', title: 'Key Questions & Next Steps', icon: '➡️' },
  ];

  const renderField = (
    label: string,
    fieldPath: string,
    type: 'text' | 'textarea' | 'date' = 'text',
    placeholder?: string,
    rows?: number
  ) => {
    const path = fieldPath.split('.');
    const value = getNestedFieldValue(data, path);
    
    const updateNestedField = (newValue: string) => {
      setData(prev => {
        const newData = { ...prev };
        let current: any = newData;
        for (let i = 0; i < path.length - 1; i++) {
          if (!current[path[i]]) {
            current[path[i]] = {};
          }
          current = current[path[i]];
        }
        current[path[path.length - 1]] = newValue;
        return newData;
      });
    };

    return (
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          {label}
        </label>
        {type === 'textarea' ? (
          <textarea
            value={value || ''}
            onChange={(e) => updateNestedField(e.target.value)}
            placeholder={placeholder}
            rows={rows || 3}
            disabled={readOnly}
            className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm disabled:bg-gray-50 disabled:text-gray-500"
          />
        ) : type === 'date' ? (
          <input
            type="date"
            value={value || ''}
            onChange={(e) => updateNestedField(e.target.value)}
            disabled={readOnly}
            className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm disabled:bg-gray-50 disabled:text-gray-500"
          />
        ) : (
          <input
            type="text"
            value={value || ''}
            onChange={(e) => updateNestedField(e.target.value)}
            placeholder={placeholder}
            disabled={readOnly}
            className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm disabled:bg-gray-50 disabled:text-gray-500"
          />
        )}
      </div>
    );
  };

  

  // Helper function to get nested field values
  const getNestedFieldValue = (obj: any, path: string[]): string => {
    let current = obj;
    for (const key of path) {
      if (current && typeof current === 'object' && key in current) {
        current = current[key];
      } else {
        return '';
      }
    }
    return typeof current === 'string' ? current : '';
  };

  const renderFinancialTable = () => (
    <div className="space-y-4">
      <h4 className="text-lg font-medium text-gray-900">Key Historical Financials</h4>
      <div className="overflow-x-auto">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Metric
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                FY-3
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                FY-2
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                FY-1
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                LTM
              </th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            <tr>
              <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                Revenue
              </td>
              {(['fy3', 'fy2', 'fy1', 'ltm'] as const).map((period) => (
                <td key={period} className="px-6 py-4 whitespace-nowrap">
                  <input
                    type="text"
                    value={data.financialSummary.financials[period].revenue}
                    onChange={(e) => updateFinancials(period, 'revenue', e.target.value)}
                    placeholder="$0"
                    disabled={readOnly}
                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm disabled:bg-gray-50 disabled:text-gray-500"
                  />
                </td>
              ))}
            </tr>
            <tr>
              <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                Revenue Growth (%)
              </td>
              {(['fy3', 'fy2', 'fy1', 'ltm'] as const).map((period) => (
                <td key={period} className="px-6 py-4 whitespace-nowrap">
                  <input
                    type="text"
                    value={data.financialSummary.financials[period].revenueGrowth}
                    onChange={(e) => updateFinancials(period, 'revenueGrowth', e.target.value)}
                    placeholder="0%"
                    disabled={readOnly}
                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm disabled:bg-gray-50 disabled:text-gray-500"
                  />
                </td>
              ))}
            </tr>
            <tr>
              <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                EBITDA
              </td>
              {(['fy3', 'fy2', 'fy1', 'ltm'] as const).map((period) => (
                <td key={period} className="px-6 py-4 whitespace-nowrap">
                  <input
                    type="text"
                    value={data.financialSummary.financials[period].ebitda}
                    onChange={(e) => updateFinancials(period, 'ebitda', e.target.value)}
                    placeholder="$0"
                    disabled={readOnly}
                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm disabled:bg-gray-50 disabled:text-gray-500"
                  />
                </td>
              ))}
            </tr>
            <tr>
              <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                EBITDA Margin (%)
              </td>
              {(['fy3', 'fy2', 'fy1', 'ltm'] as const).map((period) => (
                <td key={period} className="px-6 py-4 whitespace-nowrap">
                  <input
                    type="text"
                    value={data.financialSummary.financials[period].ebitdaMargin}
                    onChange={(e) => updateFinancials(period, 'ebitdaMargin', e.target.value)}
                    placeholder="0%"
                    disabled={readOnly}
                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm disabled:bg-gray-50 disabled:text-gray-500"
                  />
                </td>
              ))}
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  );

  const renderSection = () => {
    switch (activeSection) {
      case 'deal-overview':
        return (
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {renderField('Target Company Name', 'dealOverview.targetCompanyName')}
              {renderField('Industry/Sector', 'dealOverview.industrySector')}
              {renderField('Geography (HQ & Key Operations)', 'dealOverview.geography')}
              {renderField('Deal Source', 'dealOverview.dealSource')}
              {renderField('Transaction Type', 'dealOverview.transactionType')}
              {renderField('Date CIM Received', 'dealOverview.dateCIMReceived', 'date')}
              {renderField('Date Reviewed', 'dealOverview.dateReviewed', 'date')}
              {renderField('Reviewer(s)', 'dealOverview.reviewers')}
              {renderField('CIM Page Count', 'dealOverview.cimPageCount')}
              {renderField('Employee Count', 'dealOverview.employeeCount')}
            </div>
            {renderField('Stated Reason for Sale (if provided)', 'dealOverview.statedReasonForSale', 'textarea', 'Enter the stated reason for sale...', 4)}
          </div>
        );

      case 'business-description':
        return (
          <div className="space-y-6">
            {renderField('Core Operations Summary (3-5 sentences)', 'businessDescription.coreOperationsSummary', 'textarea', 'Describe the core operations...', 4)}
            {renderField('Key Products/Services & Revenue Mix (Est. % if available)', 'businessDescription.keyProductsServices', 'textarea', 'List key products/services and revenue mix...', 4)}
            {renderField('Unique Value Proposition (UVP) / Why Customers Buy', 'businessDescription.uniqueValueProposition', 'textarea', 'Describe the unique value proposition...', 4)}
            
            <div className="space-y-4">
              <h4 className="text-lg font-medium text-gray-900">Customer Base Overview</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {renderField('Key Customer Segments/Types', 'businessDescription.customerBaseOverview.keyCustomerSegments')}
                {renderField('Customer Concentration Risk (Top 5 and/or Top 10 Customers as % Revenue)', 'businessDescription.customerBaseOverview.customerConcentrationRisk')}
                {renderField('Typical Contract Length / Recurring Revenue %', 'businessDescription.customerBaseOverview.typicalContractLength')}
              </div>
            </div>

            <div className="space-y-4">
              <h4 className="text-lg font-medium text-gray-900">Key Supplier Overview (if critical & mentioned)</h4>
              {renderField('Dependence/Concentration Risk', 'businessDescription.keySupplierOverview.dependenceConcentrationRisk', 'textarea', 'Describe supplier dependencies...', 3)}
            </div>
          </div>
        );

      case 'market-analysis':
        return (
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {renderField('Estimated Market Size (TAM/SAM - if provided)', 'marketIndustryAnalysis.estimatedMarketSize')}
              {renderField('Estimated Market Growth Rate (% CAGR - Historical & Projected)', 'marketIndustryAnalysis.estimatedMarketGrowthRate')}
            </div>
            {renderField('Key Industry Trends & Drivers (Tailwinds/Headwinds)', 'marketIndustryAnalysis.keyIndustryTrends', 'textarea', 'Describe key industry trends...', 4)}
            
            <div className="space-y-4">
              <h4 className="text-lg font-medium text-gray-900">Competitive Landscape</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {renderField('Key Competitors Identified', 'marketIndustryAnalysis.competitiveLandscape.keyCompetitors')}
                {renderField('Target\'s Stated Market Position/Rank', 'marketIndustryAnalysis.competitiveLandscape.targetMarketPosition')}
                {renderField('Basis of Competition', 'marketIndustryAnalysis.competitiveLandscape.basisOfCompetition')}
              </div>
            </div>
            
            {renderField('Barriers to Entry / Competitive Moat (Stated/Inferred)', 'marketIndustryAnalysis.barriersToEntry', 'textarea', 'Describe barriers to entry...', 4)}
          </div>
        );

      case 'financial-summary':
        return (
          <div className="space-y-6">
            {renderFinancialTable()}
            
            <div className="space-y-4">
              <h4 className="text-lg font-medium text-gray-900">Key Financial Notes & Observations</h4>
              <div className="grid grid-cols-1 gap-6">
                {renderField('Quality of Earnings/Adjustments (Initial Impression)', 'financialSummary.qualityOfEarnings', 'textarea', 'Assess quality of earnings...', 3)}
                {renderField('Revenue Growth Drivers (Stated)', 'financialSummary.revenueGrowthDrivers', 'textarea', 'Identify revenue growth drivers...', 3)}
                {renderField('Margin Stability/Trend Analysis', 'financialSummary.marginStabilityAnalysis', 'textarea', 'Analyze margin trends...', 3)}
                {renderField('Capital Expenditures (Approx. LTM % of Revenue)', 'financialSummary.capitalExpenditures')}
                {renderField('Working Capital Intensity (Impression)', 'financialSummary.workingCapitalIntensity', 'textarea', 'Assess working capital intensity...', 3)}
                {renderField('Free Cash Flow (FCF) Proxy Quality (Impression)', 'financialSummary.freeCashFlowQuality', 'textarea', 'Assess FCF quality...', 3)}
              </div>
            </div>
          </div>
        );

      case 'management-team':
        return (
          <div className="space-y-6">
            {renderField('Key Leaders Identified (CEO, CFO, COO, Head of Sales, etc.)', 'managementTeamOverview.keyLeaders', 'textarea', 'List key leaders...', 4)}
            {renderField('Initial Assessment of Quality/Experience (Based on Bios)', 'managementTeamOverview.managementQualityAssessment', 'textarea', 'Assess management quality...', 4)}
            {renderField('Management\'s Stated Post-Transaction Role/Intentions (if mentioned)', 'managementTeamOverview.postTransactionIntentions', 'textarea', 'Describe post-transaction intentions...', 4)}
            {renderField('Organizational Structure Overview (Impression)', 'managementTeamOverview.organizationalStructure', 'textarea', 'Describe organizational structure...', 4)}
          </div>
        );

      case 'investment-thesis':
        return (
          <div className="space-y-6">
            {renderField('Key Attractions / Strengths (Why Invest?)', 'preliminaryInvestmentThesis.keyAttractions', 'textarea', 'List key attractions...', 4)}
            {renderField('Potential Risks / Concerns (Why Not Invest?)', 'preliminaryInvestmentThesis.potentialRisks', 'textarea', 'List potential risks...', 4)}
            {renderField('Initial Value Creation Levers (How PE Adds Value)', 'preliminaryInvestmentThesis.valueCreationLevers', 'textarea', 'Identify value creation levers...', 4)}
            {renderField('Alignment with Fund Strategy', 'preliminaryInvestmentThesis.alignmentWithFundStrategy', 'textarea', 'Assess alignment with BPCP strategy...', 4)}
          </div>
        );

      case 'next-steps':
        return (
          <div className="space-y-6">
            {renderField('Critical Questions Arising from CIM Review', 'keyQuestionsNextSteps.criticalQuestions', 'textarea', 'List critical questions...', 4)}
            {renderField('Key Missing Information / Areas for Diligence Focus', 'keyQuestionsNextSteps.missingInformation', 'textarea', 'Identify missing information...', 4)}
            {renderField('Preliminary Recommendation', 'keyQuestionsNextSteps.preliminaryRecommendation')}
            {renderField('Rationale for Recommendation (Brief)', 'keyQuestionsNextSteps.rationaleForRecommendation', 'textarea', 'Provide rationale...', 4)}
            {renderField('Proposed Next Steps', 'keyQuestionsNextSteps.proposedNextSteps', 'textarea', 'Outline next steps...', 4)}
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="max-w-7xl mx-auto">
      {/* Header */}
      <div className="bg-white shadow-sm border-b border-gray-200 px-4 py-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">BPCP CIM Review Template</h1>
            <p className="text-sm text-gray-600 mt-1">
              Comprehensive review template for Confidential Information Memorandums
            </p>
          </div>
          <div className="flex items-center space-x-3">
            {!readOnly && (
              <button
                onClick={handleSave}
                className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
              >
                <Save className="h-4 w-4 mr-2" />
                Save
              </button>
            )}
            <button
              onClick={handleExport}
              className="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
            >
              <Download className="h-4 w-4 mr-2" />
              Export
            </button>
          </div>
        </div>
      </div>

      <div className="flex">
        {/* Sidebar Navigation */}
        <div className="w-64 bg-gray-50 border-r border-gray-200 min-h-screen">
          <nav className="mt-5 px-2">
            <div className="space-y-1">
              {sections.map((section) => (
                <button
                  key={section.id}
                  onClick={() => setActiveSection(section.id)}
                  className={cn(
                    'group flex items-center px-3 py-2 text-sm font-medium rounded-md w-full text-left',
                    activeSection === section.id
                      ? 'bg-blue-100 text-blue-700'
                      : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900'
                  )}
                >
                  <span className="mr-3">{section.icon}</span>
                  {section.title}
                </button>
              ))}
            </div>
          </nav>
        </div>

        {/* Main Content */}
        <div className="flex-1 bg-white">
          <div className="px-4 py-6 sm:px-6 lg:px-8">
            <div className="max-w-4xl">
              {renderSection()}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CIMReviewTemplate; 