'use client';

import { useState, useEffect } from 'react';
import { Settings, Package, Palette, Link2, Mail, Monitor, FileCheck, DollarSign, Zap, Users, Plus, X, Save, Pencil, Trash2, FileText, Battery } from 'lucide-react';
import RichTextEditor from '@/components/RichTextEditor';
import GeneralSettings from './components/GeneralSettings';
import BrandingSettings from './components/BrandingSettings';
import SocialSettings from './components/SocialSettings';
import IntegrationSettings from './components/IntegrationSettings';
import LandingSettings from './components/LandingSettings';
import KycSettings from './components/KycSettings';
import PartsSettings from './components/PartsSettings';
import CompanyPolicySettings from './components/CompanyPolicySettings';
import PlanSelection from './components/PlanSelection';
import InvestmentSettings from './components/InvestmentSettings';
import BatteryInvestmentSettings from './components/BatteryInvestmentSettings';
import SwapStationSettings from './components/SwapStationSettings';
import RiderRequestSettings from './components/RiderRequestSettings';
import EmailSMSTemplates from './components/EmailSMSTemplates';

export interface CompanySettings {
  name: string;
  shortName: string;
  tagLine: string;
  description: string;
  email: string;
  phone: string;
  website: string;
  address: string;
  city: string;
  country: string;
  tin: string;
  bin: string;
  tradeLicense: string;
  timezone: string;
  currency: string;
  language: string;
  logo: string;
  favicon: string;
  primaryColor: string;
  secondaryColor: string;
  borderRadius: number;
  socialLinks: {
    facebook: string;
    twitter: string;
    instagram: string;
    linkedin: string;
    youtube: string;
  };
  smtp: {
    host: string;
    port: number;
    user: string;
    password: string;
    fromEmail: string;
    fromName: string;
    encryption: 'ssl' | 'tls' | 'none';
  };
  sms: {
    provider: string;
    apiKey: string;
    senderId: string;
    url: string;
  };
  heroData: {
    title: string;
    subtitle: string;
    ctaText: string;
    ctaLink: string;
    videoUrl: string;
    backgroundImage: string;
  };
  masterData: {
    kycDocuments: { name: string; required: boolean }[];
    riderDocuments: { id: string; name: string; required: boolean; description: string }[];
    subscriptionPlans: { name: string; price: number; duration: number; features: string[] }[];
    rentalPlans: { id: string; name: string; type: string; description: string; price: number; duration: number }[];
    investorDocuments: { id: string; name: string; required: boolean; description: string }[];
    merchantDocuments: { id: string; name: string; required: boolean; description: string }[];
    swapStationDocuments: { id: string; name: string; required: boolean; description: string }[];
    rentalDocuments: {
      type: 'single' | 'shared' | 'rent-to-own';
      name: string;
      documents: { id: string; name: string; required: boolean; description: string }[];
    }[];
  };
  parts: { id: string; name: string; buyingPrice: number; sellingPrice: number }[];
  serviceCenters: { id: string; name: string; address: string; phone: string; rating: number }[];
  companyPolicy: {
    investor: { title: string; description: string; showApp: boolean; showWeb: boolean }[];
    merchant: { title: string; description: string; showApp: boolean; showWeb: boolean }[];
    swapStation: { title: string; description: string; showApp: boolean; showWeb: boolean }[];
    rentalTypes: {
      single: { title: string; description: string; showApp: boolean; showWeb: boolean }[];
      shared: { title: string; description: string; showApp: boolean; showWeb: boolean }[];
      renttoown: { title: string; description: string; showApp: boolean; showWeb: boolean }[];
    };
  };
  rentalPolicy: {
    minAge: number;
    requireLicense: boolean;
    deposit: number;
    lateFeePerHour: number;
    cancellationFee: number;
    damagePenalty: { level: string; amount: number }[];
    rules: string[];
  };
  plans: {
    singleRent: {
      id: string;
      name: string;
      evModels: string[];
      contractMonths: number[];
      dailyRent: number;
      dailyRentPenalty1: number;
      dailyRentPenalty2: number;
      dailyRentPenalty3: number;
      deposit: number;
      weeklySubscription: number;
      weeklyPenalty1: number;
      weeklyPenalty2: number;
      weeklyPenalty3: number;
      monthlySubscription: number;
      monthlyPenalty1: number;
      monthlyPenalty2: number;
      monthlyPenalty3: number;
      ficoSharePercent: number;
      freeServiceConditions: { months: number; freeServices: number }[];
      description: string;
    }[];
    rentToOwn: {
      id: string;
      name: string;
      evModels: string[];
      contractMonths: number[];
      dailyRent: number;
      dailyRentPenalty1: number;
      dailyRentPenalty2: number;
      dailyRentPenalty3: number;
      deposit: number;
      weeklySubscription: number;
      weeklyPenalty1: number;
      weeklyPenalty2: number;
      weeklyPenalty3: number;
      monthlySubscription: number;
      monthlyPenalty1: number;
      monthlyPenalty2: number;
      monthlyPenalty3: number;
      durationMonths: number;
      evPrice: number;
      totalPayment: number;
      profit: number;
      ficoRentSharePercent: number;
      ficoProfitSharePercent: number;
      freeServiceConditions: { months: number; freeServices: number }[];
      description: string;
    }[];
    shareEv: {
      id: string;
      name: string;
      evModels: string[];
      contractMonths: number[];
      dailyRentEach: number;
      dailyRentPenalty1: number;
      dailyRentPenalty2: number;
      dailyRentPenalty3: number;
      totalDailyRent: number;
      depositEach: number;
      depositPenalty1: number;
      depositPenalty2: number;
      depositPenalty3: number;
      totalDeposit: number;
      weeklySubscriptionEach: number;
      weeklyPenalty1: number;
      weeklyPenalty2: number;
      weeklyPenalty3: number;
      totalWeeklySubscription: number;
      monthlySubscriptionEach: number;
      monthlyPenalty1: number;
      monthlyPenalty2: number;
      monthlyPenalty3: number;
      totalMonthlySubscription: number;
      ficoSharePercent: number;
      freeServiceConditions: { months: number; freeServices: number }[];
      description: string;
    }[];
    investment: {
      id: string;
      tier: string;
      name: string;
      minQuantity: number;
      evBasePrice: number;
      minInvestment: number;
      maxInvestment: number;
      durationMonths: number;
      profitSharePercent: number;
      lockInMonths: number;
      earlyExitPenalty: number;
      startDate: string;
      endDate: string;
      targetAmount: number;
      status: string;
      description: string;
      ficoSingleRent: number;
      ficoRentToOwn: number;
      ficoShareEv: number;
    }[];
    batteryInvestment: {
      id: string;
      tier: string;
      name: string;
      minQuantity: number;
      batteryBasePrice: number;
      minInvestment: number;
      maxInvestment: number;
      durationMonths: number;
      profitSharePercent: number;
      lockInMonths: number;
      earlyExitPenalty: number;
      startDate: string;
      endDate: string;
      targetAmount: number;
      status: string;
      description: string;
    }[];
    swapStation: {
      id: string;
      name: string;
      batteryCount: number;
      swapPrice: number;
      monthlySubscription: number;
      dailySubscription: number;
      minBatteries: number;
      maxBatteries: number;
      profitSharePercent: number;
      status: string;
      description: string;
    }[];
    riderRequest: {
      id: string;
      tier: string;
      name: string;
      minRiders: number;
      maxRiders: number;
      monthlySubscription: number;
      dailySubscription: number;
      deposit: number;
      commissionPercent: number;
      dailyRideTarget: number;
      weeklyHoliday: number;
      status: string;
      description: string;
    }[];
  };
}

const initialSettings: CompanySettings = {
  name: 'JAIBEN Mobility Ltd',
  shortName: 'JAIBEN',
  tagLine: 'Your Trusted EV Mobility Partner',
  description: 'Leading electric vehicle rental and swap station network in Bangladesh',
  email: 'info@jaiben.com',
  phone: '+880 9611-222-333',
  website: 'https://jaiben.com',
  address: 'House 45, Road 13, Gulshan 1',
  city: 'Dhaka',
  country: 'Bangladesh',
  tin: '123456789012',
  bin: '987654321098',
  tradeLicense: 'TRAD/2023/001234',
  timezone: 'Asia/Dhaka',
  currency: 'BDT',
  language: 'en',
  logo: '/logo.png',
  favicon: '/favicon.ico',
  primaryColor: '#10B981',
  secondaryColor: '#3B82F6',
  borderRadius: 8,
  socialLinks: {
    facebook: 'https://facebook.com/jaiben',
    twitter: 'https://twitter.com/jaiben',
    instagram: 'https://instagram.com/jaiben',
    linkedin: 'https://linkedin.com/company/jaiben',
    youtube: 'https://youtube.com/@jaiben'
  },
  smtp: {
    host: 'smtp.mailserver.com',
    port: 587,
    user: 'noreply@jaiben.com',
    password: '••••••••••••',
    fromEmail: 'noreply@jaiben.com',
    fromName: 'JAIBEN Mobility',
    encryption: 'tls'
  },
  sms: {
    provider: 'BulkSMS',
    apiKey: '••••••••••••••••',
    senderId: 'JAIBEN',
    url: 'https://api.bulksmsbd.com'
  },
  heroData: {
    title: 'Welcome to JAIBEN',
    subtitle: 'Your trusted partner for electric vehicle mobility solutions across Bangladesh',
    ctaText: 'Get Started',
    ctaLink: '/rent',
    videoUrl: '',
    backgroundImage: '/hero-bg.jpg'
  },
  masterData: {
    kycDocuments: [
      { name: 'NID Card', required: true },
      { name: 'Driving License', required: true },
      { name: 'Passport Photo', required: true },
      { name: 'Address Proof', required: false },
      { name: 'Business Trade License', required: false },
    ],
    riderDocuments: [
      { id: 'rider_nid_front', name: 'NID (Front)', required: true, description: 'National ID card front side' },
      { id: 'rider_nid_back', name: 'NID (Back)', required: true, description: 'National ID card back side' },
      { id: 'rider_license', name: 'Driving License', required: true, description: 'Valid driving license' },
      { id: 'rider_photo', name: 'Profile Photo', required: true, description: 'Recent passport size photo' },
      { id: 'rider_bank_card', name: 'Bank Account Card', required: false, description: 'Bank account card/cheque' },
      { id: 'rider_wallet', name: 'Mobile Wallet Info', required: false, description: 'bKash/Rocket account details' },
    ],
    subscriptionPlans: [
      { name: 'Daily', price: 500, duration: 1, features: ['24 hours access', 'Basic support'] },
      { name: 'Weekly', price: 3000, duration: 7, features: ['7 days access', 'Priority support', 'Free swap'] },
      { name: 'Monthly', price: 10000, duration: 30, features: ['30 days access', 'VIP support', 'Unlimited swap', 'Damage coverage'] },
      { name: 'Yearly', price: 80000, duration: 365, features: ['1 year access', 'Dedicated manager', 'Unlimited swap', 'Full coverage', 'Discounted rates'] },
    ],
    rentalPlans: [
      { id: 'single_rent', name: 'Single Rent', type: 'single', description: 'Single person rental plan', price: 500, duration: 1 },
      { id: 'weekly_rent', name: 'Weekly Rent', type: 'weekly', description: '7 days rental plan', price: 3000, duration: 7 },
      { id: 'monthly_rent', name: 'Monthly Rent', type: 'monthly', description: '30 days rental plan', price: 10000, duration: 30 },
      { id: 'rent_to_own', name: 'Rent to Own', type: 'rent-to-own', description: 'Own after X months', price: 15000, duration: 365 },
      { id: 'share_ev', name: 'Share EV', type: 'shared', description: 'Shared bike', price: 2500, duration: 30 },
    ],
    investorDocuments: [
      { id: 'inv_nid', name: 'NID Card (Front & Back)', required: true, description: 'National ID card copy' },
      { id: 'inv_photo', name: 'Passport Size Photo', required: true, description: 'Recent passport size photograph' },
      { id: 'inv_bank', name: 'Bank Account Info', required: true, description: 'Bank account details for earnings' },
      { id: 'inv_mobile', name: 'Mobile Banking', required: true, description: 'bKash/Rocket account details' },
      { id: 'inv_tin', name: 'TIN Certificate', required: false, description: 'Tax Identification Number' },
      { id: 'inv_tax', name: 'Tax Return', required: false, description: 'Recent tax return copy' },
      { id: 'inv_ec', name: 'Emergency Contact ID', required: false, description: 'Emergency contact NID copy' },
    ],
    merchantDocuments: [
      { id: 'mer_trade', name: 'Trade License', required: true, description: 'Business trade license' },
      { id: 'mer_nid', name: 'Owner NID Card', required: true, description: 'Owner/proprietor NID card' },
      { id: 'mer_photo', name: 'Shop Photo', required: true, description: 'Photo of shop premises' },
      { id: 'mer_tin', name: 'TIN Certificate', required: true, description: 'Tax Identification Number' },
      { id: 'mer_bank', name: 'Bank Account Info', required: true, description: 'Business bank account' },
      { id: 'mer_agreement', name: 'Shop Agreement', required: false, description: 'Rent agreement or ownership' },
      { id: 'mer_fire', name: 'Fire License', required: false, description: 'Fire safety license' },
    ],
    swapStationDocuments: [
      { id: 'ss_trade', name: 'Trade License', required: true, description: 'Business trade license' },
      { id: 'ss_owner_nid', name: 'Owner NID Card', required: true, description: 'Proprietor NID card' },
      { id: 'ss_photo', name: 'Station Photo', required: true, description: 'Photo of swap station' },
      { id: 'ss_tin', name: 'TIN Certificate', required: true, description: 'Tax Identification Number' },
      { id: 'ss_electric', name: 'Electricity Bill', required: true, description: 'Recent electricity bill' },
      { id: 'ss_agreement', name: 'Space Agreement', required: false, description: 'Rent/space agreement' },
      { id: 'ss_safety', name: 'Safety Certificate', required: false, description: 'Electrical safety certificate' },
    ],
    rentalDocuments: [
      {
        type: 'single',
        name: 'Rental (Single)',
        documents: [
          { id: 'rent_nid', name: 'NID Card', required: true, description: 'Valid National ID' },
          { id: 'rent_license', name: 'Driving License', required: true, description: 'Valid driving license' },
          { id: 'rent_photo', name: 'Passport Photo', required: true, description: 'Recent photo' },
          { id: 'rent_deposit', name: 'Deposit Receipt', required: true, description: 'Security deposit proof' },
          { id: 'rent_ec', name: 'Emergency Contact', required: true, description: 'Emergency contact info' },
        ]
      },
      {
        type: 'shared',
        name: 'Rental (2 Person Shared)',
        documents: [
          { id: 'rent_nid_1', name: 'Rider 1 - NID Card', required: true, description: 'Primary rider NID' },
          { id: 'rent_license_1', name: 'Rider 1 - Driving License', required: true, description: 'Primary rider license' },
          { id: 'rent_nid_2', name: 'Rider 2 - NID Card', required: true, description: 'Secondary rider NID' },
          { id: 'rent_license_2', name: 'Rider 2 - Driving License', required: true, description: 'Secondary rider license' },
          { id: 'rent_photo', name: 'Passport Photos (Both)', required: true, description: 'Photos of both riders' },
          { id: 'rent_deposit', name: 'Deposit Receipt', required: true, description: 'Security deposit proof' },
          { id: 'rent_agreement', name: 'Shared Agreement', required: true, description: 'Agreement between riders' },
          { id: 'rent_ec', name: 'Emergency Contacts', required: true, description: 'Emergency contacts for both' },
        ]
      },
      {
        type: 'rent-to-own',
        name: 'Rent-to-Own',
        documents: [
          { id: 'rto_nid', name: 'NID Card', required: true, description: 'Valid National ID' },
          { id: 'rto_license', name: 'Driving License', required: true, description: 'Valid driving license' },
          { id: 'rto_photo', name: 'Passport Photo', required: true, description: 'Recent photo' },
          { id: 'rto_income', name: 'Income Proof', required: true, description: 'Salary/income certificate' },
          { id: 'rto_bank', name: 'Bank Statement', required: true, description: '6 months bank statement' },
          { id: 'rto_tin', name: 'TIN Certificate', required: false, description: 'Tax Identification Number' },
          { id: 'rto_guarantor', name: 'Guarantor Info', required: true, description: 'Guarantor details' },
          { id: 'rto_guarantor_nid', name: 'Guarantor NID', required: true, description: 'Guarantor NID copy' },
          { id: 'rto_agreement', name: 'RTO Agreement', required: true, description: 'Rent-to-own contract' },
          { id: 'rto_insurance', name: 'Insurance', required: false, description: 'Vehicle insurance' },
        ]
      },
    ]
  },
  parts: [
    { id: 'PRT-001', name: 'Battery 60V', buyingPrice: 12000, sellingPrice: 15000 },
    { id: 'PRT-002', name: 'Battery 48V', buyingPrice: 9000, sellingPrice: 12000 },
    { id: 'PRT-003', name: 'Front Tire', buyingPrice: 1800, sellingPrice: 2500 },
    { id: 'PRT-004', name: 'Rear Tire', buyingPrice: 1800, sellingPrice: 2500 },
    { id: 'PRT-005', name: 'Brake Pad', buyingPrice: 500, sellingPrice: 800 },
    { id: 'PRT-006', name: 'Mirror', buyingPrice: 200, sellingPrice: 350 },
    { id: 'PRT-007', name: 'Controller', buyingPrice: 3000, sellingPrice: 4500 },
    { id: 'PRT-008', name: 'Motor', buyingPrice: 7000, sellingPrice: 10000 },
    { id: 'PRT-009', name: 'Charger', buyingPrice: 1200, sellingPrice: 2000 },
    { id: 'PRT-010', name: 'Display Meter', buyingPrice: 800, sellingPrice: 1200 },
    { id: 'PRT-011', name: 'Throttle', buyingPrice: 500, sellingPrice: 800 },
    { id: 'PRT-012', name: 'Brake Cable', buyingPrice: 150, sellingPrice: 250 },
    { id: 'PRT-013', name: 'Chain', buyingPrice: 400, sellingPrice: 600 },
    { id: 'PRT-014', name: 'Sprocket', buyingPrice: 300, sellingPrice: 450 },
    { id: 'PRT-015', name: 'Foot Peg', buyingPrice: 180, sellingPrice: 300 },
  ],
  serviceCenters: [
    { id: 'SC-001', name: 'JAIBEN Service Center - Gulshan', address: 'House 45, Road 13, Gulshan 1, Dhaka', phone: '+8801712345670', rating: 4.8 },
    { id: 'SC-002', name: 'JAIBEN Service Center - Banani', address: 'Road 11, Banani, Dhaka', phone: '+8801712345671', rating: 4.5 },
  ],
  companyPolicy: {
    investor: [
      { title: 'Investor Policy', description: '<h2>Investor Guidelines</h2><p>Welcome to our investor program. This document outlines the terms and conditions for all investors participating in our EV fleet sharing initiative.</p><h3>Key Requirements</h3><ul><li>All investors must complete KYC verification</li><li>Minimum investment amount: ৳100,000</li><li>Monthly returns are calculated based on fleet utilization</li></ul><p><strong>Note:</strong> Past performance does not guarantee future results. Please read all terms carefully before investing.</p>', showApp: true, showWeb: true },
      { title: 'Investor Risk Policy', description: '<h2>Risk Disclosure</h2><p>All investments carry risk. Past performance does not guarantee future results.</p><h3>Risk Factors</h3><ul><li>Market fluctuations</li><li>Operational risks</li><li>Regulatory changes</li></ul>', showApp: true, showWeb: false },
      { title: 'Investor Returns Policy', description: '<h2>Returns</h2><p>Returns depend on fleet performance and utilization.</p><h3>Return Calculation</h3><ul><li>Monthly returns: 2-5%</li><li>Quarterly settlements</li><li>Annual statements</li></ul>', showApp: true, showWeb: true }
    ],
    merchant: [
      { title: 'Merchant Policy', description: '<h2>Merchant Terms</h2><p>Thank you for joining our merchant network. These guidelines ensure smooth operations.</p><h3>Operational Requirements</h3><ul><li>Maintain minimum inventory levels</li><li>Provide excellent customer service</li><li>Accept all payment methods</li></ul>', showApp: true, showWeb: true },
      { title: 'Merchant SLA Policy', description: '<h2>Service Level Agreement</h2><p>Orders must be processed within 24 hours.</p><h3>Response Time</h3><ul><li>Order confirmation: Within 2 hours</li><li>Delivery: Within 24 hours</li><li>Support: Within 4 hours</li></ul>', showApp: true, showWeb: false },
      { title: 'Merchant Commission Policy', description: '<h2>Commission</h2><p>Merchants earn 15% commission per order.</p><h3>Commission Structure</h3><ul><li>Standard orders: 15%</li><li>Bulk orders: 18%</li><li>Premium merchants: 20%</li></ul>', showApp: true, showWeb: true }
    ],
    swapStation: [
      { title: 'Swap Station Policy', description: '<h2>Swap Guidelines</h2><p>Follow safety protocols when handling batteries.</p><h3>General Guidelines</h3><ul><li>Wear protective gloves</li><li>Inspect batteries before swapping</li><li>Keep area clean</li></ul>', showApp: true, showWeb: true },
      { title: 'Battery Safety Policy', description: '<h2>Battery Handling</h2><p>Use gloves and inspect batteries before and after swapping.</p><h3>Safety Measures</h3><ul><li>Check for physical damage</li><li>Verify charge level</li><li>Report malfunctions</li></ul>', showApp: true, showWeb: false },
      { title: 'Maintenance Policy', description: '<h2>Maintenance</h2><p>Keep stations clean and operational at all times.</p><h3>Daily Tasks</h3><ul><li>Clean charging pads</li><li>Check cable conditions</li><li>Update system software</li></ul>', showApp: true, showWeb: true }
    ],
    rentalTypes: {
      single: [
        { title: 'Rental (Single)', description: '<h2>Single Rental</h2><p>Perfect for individual riders who need a reliable vehicle for daily commute or delivery work.</p><h3>Plan Features</h3><ul><li>Daily, weekly, and monthly options</li><li>Comprehensive insurance included</li><li>24/7 roadside assistance</li></ul>', showApp: true, showWeb: true },
        { title: 'Single Rental Pricing', description: '<h2>Pricing</h2><p>Starts from ৳400/day with ৳5,000 deposit.</p><h3>Rates</h3><ul><li>Daily: ৳400</li><li>Weekly: ৳2,800</li><li>Monthly: ৳12,000</li></ul>', showApp: true, showWeb: false },
        { title: 'Single Rental Benefits', description: '<h2>Benefits</h2><p>Includes maintenance, insurance, and support.</p><h3>Included</h3><ul><li>Free maintenance</li><li>Full insurance coverage</li><li>24/7 customer support</li></ul>', showApp: true, showWeb: true }
      ],
      shared: [
        { title: 'Rental (2 Person Shared)', description: '<h2>Shared Plan</h2><p>Two riders share cost and responsibilities.</p><h3>Plan Features</h3><ul><li>Split costs between two riders</li><li>Both users must be verified</li><li>Shared liability coverage</li></ul>', showApp: true, showWeb: true },
        { title: 'Shared Plan Benefits', description: '<h2>Benefits</h2><p>Split payment and flexible usage.</p><h3>Advantages</h3><ul><li>50% cost savings</li><li>Flexible driver switching</li><li>Shared deposit</li></ul>', showApp: true, showWeb: false },
        { title: 'Shared Pricing', description: '<h2>Pricing</h2><p>৳600/day total (৳300 each).</p><h3>Rates</h3><ul><li>Daily: ৳600 (৳300 each)</li><li>Weekly: ৳4,200 (৳2,100 each)</li><li>Monthly: ৳16,800 (৳8,400 each)</li></ul>', showApp: true, showWeb: true }
      ],
      renttoown: [
        { title: 'Rent-to-Own', description: '<h2>Ownership Plan</h2><p>Own vehicle after completing payment tenure.</p><h3>Program Benefits</h3><ul><li>50% payments go toward purchase</li><li>Option to buyout anytime</li><li>Full ownership after 36 months</li></ul>', showApp: true, showWeb: true },
        { title: 'Eligibility', description: '<h2>Eligibility</h2><p>Requires good payment history.</p><h3>Requirements</h3><ul><li>Credit check applies</li><li>Stable income proof</li><li>Minimum 6 months tenure</li></ul>', showApp: true, showWeb: false },
        { title: 'Ownership Benefits', description: '<h2>Benefits</h2><p>50% of payments go toward vehicle purchase.</p><h3>Advantages</h3><ul><li>Transferable to family</li><li>No hidden costs</li><li>Full warranty included</li></ul>', showApp: true, showWeb: true }
      ]
    },
  },
  rentalPolicy: {
    minAge: 18,
    requireLicense: true,
    deposit: 5000,
    lateFeePerHour: 200,
    cancellationFee: 1000,
    damagePenalty: [
      { level: 'Minor Scratch', amount: 500 },
      { level: 'Major Damage', amount: 5000 },
      { level: 'Total Loss', amount: 25000 },
    ],
    rules: [
      'No smoking in vehicles',
      'Return with same fuel/charge level',
      'No unauthorized drivers',
      'Follow traffic rules',
      'Report accidents within 24 hours',
    ]
  },
  plans: {
    singleRent: [
      {
        id: 'sr-1',
        name: 'Single Rent - Premium',
        evModels: [],
        contractMonths: [1, 3, 6, 12],
        dailyRent: 400,
        dailyRentPenalty1: 500,
        dailyRentPenalty2: 1000,
        dailyRentPenalty3: 5000,
        deposit: 25000,
        weeklySubscription: 2800,
        weeklyPenalty1: 3500,
        weeklyPenalty2: 7000,
        weeklyPenalty3: 15000,
        monthlySubscription: 12000,
        monthlyPenalty1: 15000,
        monthlyPenalty2: 30000,
        monthlyPenalty3: 50000,
        ficoSharePercent: 50,
        freeServiceConditions: [
          { months: 3, freeServices: 2 },
          { months: 6, freeServices: 4 },
        ],
        description: 'Premium single person rental plan with extra benefits',
      },
      {
        id: 'sr-2',
        name: 'Single Rent - Standard',
        evModels: [],
        contractMonths: [1, 3, 6, 12],
        dailyRent: 300,
        dailyRentPenalty1: 400,
        dailyRentPenalty2: 800,
        dailyRentPenalty3: 4000,
        deposit: 20000,
        weeklySubscription: 2100,
        weeklyPenalty1: 2600,
        weeklyPenalty2: 5200,
        weeklyPenalty3: 12000,
        monthlySubscription: 9000,
        monthlyPenalty1: 11000,
        monthlyPenalty2: 22000,
        monthlyPenalty3: 40000,
        ficoSharePercent: 45,
        freeServiceConditions: [
          { months: 2, freeServices: 1 },
          { months: 3, freeServices: 2 },
        ],
        description: 'Standard single person rental plan',
      },
      {
        id: 'sr-3',
        name: 'Single Rent - Economy',
        evModels: [],
        contractMonths: [1, 3, 6, 12],
        dailyRent: 250,
        dailyRentPenalty1: 300,
        dailyRentPenalty2: 600,
        dailyRentPenalty3: 3000,
        deposit: 15000,
        weeklySubscription: 1750,
        weeklyPenalty1: 2200,
        weeklyPenalty2: 4000,
        weeklyPenalty3: 8000,
        monthlySubscription: 7500,
        monthlyPenalty1: 9000,
        monthlyPenalty2: 18000,
        monthlyPenalty3: 30000,
        ficoSharePercent: 40,
        freeServiceConditions: [
          { months: 2, freeServices: 1 },
        ],
        description: 'Economy single person rental plan',
      }
    ],
    rentToOwn: [
      {
        id: 'rto-1',
        name: 'Rent to Own - Premium',
        evModels: [],
        contractMonths: [12, 18, 24, 36],
        dailyRent: 350,
        dailyRentPenalty1: 450,
        dailyRentPenalty2: 900,
        dailyRentPenalty3: 4500,
        deposit: 25000,
        weeklySubscription: 2450,
        weeklyPenalty1: 3000,
        weeklyPenalty2: 6000,
        weeklyPenalty3: 15000,
        monthlySubscription: 10500,
        monthlyPenalty1: 13000,
        monthlyPenalty2: 26000,
        monthlyPenalty3: 45000,
        durationMonths: 18,
        evPrice: 150000,
        totalPayment: 170000,
        profit: 20000,
        ficoRentSharePercent: 50,
        ficoProfitSharePercent: 45,
        freeServiceConditions: [
          { months: 3, freeServices: 2 },
          { months: 6, freeServices: 4 },
        ],
        description: 'Premium rent to own plan with high-end EV',
      },
      {
        id: 'rto-2',
        name: 'Rent to Own - Standard',
        evModels: [],
        contractMonths: [12, 18, 24, 36],
        dailyRent: 250,
        dailyRentPenalty1: 350,
        dailyRentPenalty2: 700,
        dailyRentPenalty3: 3500,
        deposit: 18000,
        weeklySubscription: 1750,
        weeklyPenalty1: 2200,
        weeklyPenalty2: 4400,
        weeklyPenalty3: 10000,
        monthlySubscription: 7000,
        monthlyPenalty1: 9000,
        monthlyPenalty2: 18000,
        monthlyPenalty3: 30000,
        durationMonths: 18,
        evPrice: 120000,
        totalPayment: 135000,
        profit: 15000,
        ficoRentSharePercent: 45,
        ficoProfitSharePercent: 45,
        freeServiceConditions: [
          { months: 2, freeServices: 1 },
          { months: 3, freeServices: 2 },
        ],
        description: 'Standard rent to own plan',
      },
      {
        id: 'rto-3',
        name: 'Rent to Own - Economy',
        evModels: [],
        contractMonths: [12, 18, 24, 36],
        dailyRent: 200,
        dailyRentPenalty1: 250,
        dailyRentPenalty2: 500,
        dailyRentPenalty3: 2500,
        deposit: 15000,
        weeklySubscription: 1400,
        weeklyPenalty1: 1800,
        weeklyPenalty2: 3500,
        weeklyPenalty3: 8000,
        monthlySubscription: 6000,
        monthlyPenalty1: 7500,
        monthlyPenalty2: 15000,
        monthlyPenalty3: 25000,
        durationMonths: 18,
        evPrice: 100000,
        totalPayment: 115000,
        profit: 15000,
        ficoRentSharePercent: 40,
        ficoProfitSharePercent: 40,
        freeServiceConditions: [
          { months: 2, freeServices: 1 },
        ],
        description: 'Economy rent to own plan',
      }
    ],
    shareEv: [
      {
        id: 'se-1',
        name: 'Share an EV - Premium',
        evModels: [],
        contractMonths: [1, 3, 6, 12],
        dailyRentEach: 300,
        dailyRentPenalty1: 400,
        dailyRentPenalty2: 800,
        dailyRentPenalty3: 4000,
        totalDailyRent: 600,
        depositEach: 20000,
        depositPenalty1: 25000,
        depositPenalty2: 35000,
        depositPenalty3: 50000,
        totalDeposit: 40000,
        weeklySubscriptionEach: 2100,
        weeklyPenalty1: 2600,
        weeklyPenalty2: 5200,
        weeklyPenalty3: 12000,
        totalWeeklySubscription: 4200,
        monthlySubscriptionEach: 8400,
        monthlyPenalty1: 10500,
        monthlyPenalty2: 21000,
        monthlyPenalty3: 35000,
        totalMonthlySubscription: 16800,
        ficoSharePercent: 50,
        freeServiceConditions: [
          { months: 3, freeServices: 2 },
          { months: 6, freeServices: 4 },
        ],
        description: 'Premium shared EV with premium bikes',
      },
      {
        id: 'se-2',
        name: 'Share an EV - Standard',
        evModels: [],
        contractMonths: [1, 3, 6, 12],
        dailyRentEach: 200,
        dailyRentPenalty1: 250,
        dailyRentPenalty2: 500,
        dailyRentPenalty3: 2500,
        totalDailyRent: 400,
        depositEach: 15000,
        depositPenalty1: 18000,
        depositPenalty2: 25000,
        depositPenalty3: 40000,
        totalDeposit: 30000,
        weeklySubscriptionEach: 1400,
        weeklyPenalty1: 1800,
        weeklyPenalty2: 3500,
        weeklyPenalty3: 8000,
        totalWeeklySubscription: 2800,
        monthlySubscriptionEach: 5600,
        monthlyPenalty1: 7000,
        monthlyPenalty2: 14000,
        monthlyPenalty3: 25000,
        totalMonthlySubscription: 11200,
        ficoSharePercent: 45,
        freeServiceConditions: [
          { months: 2, freeServices: 1 },
          { months: 3, freeServices: 2 },
        ],
        description: 'Standard shared EV plan',
      },
      {
        id: 'se-3',
        name: 'Share an EV - Economy',
        evModels: [],
        contractMonths: [1, 3, 6, 12],
        dailyRentEach: 150,
        dailyRentPenalty1: 200,
        dailyRentPenalty2: 400,
        dailyRentPenalty3: 2000,
        totalDailyRent: 300,
        depositEach: 12000,
        depositPenalty1: 15000,
        depositPenalty2: 20000,
        depositPenalty3: 30000,
        totalDeposit: 24000,
        weeklySubscriptionEach: 1050,
        weeklyPenalty1: 1300,
        weeklyPenalty2: 2600,
        weeklyPenalty3: 6000,
        totalWeeklySubscription: 2100,
        monthlySubscriptionEach: 4200,
        monthlyPenalty1: 5500,
        monthlyPenalty2: 11000,
        monthlyPenalty3: 20000,
        totalMonthlySubscription: 8400,
        ficoSharePercent: 40,
        freeServiceConditions: [
          { months: 2, freeServices: 1 },
        ],
        description: 'Economy shared EV plan',
      }
    ],
    investment: [
      {
        id: 'inv_demo_1',
        name: '1 Bike Plan',
        tier: 'Economy',
        minQuantity: 1,
        evBasePrice: 200000,
        minInvestment: 200000,
        maxInvestment: 1000000,
        durationMonths: 12,
        profitSharePercent: 50,
        lockInMonths: 3,
        earlyExitPenalty: 10,
        startDate: '2026-01-01',
        endDate: '2026-12-31',
        targetAmount: 1000000,
        status: 'active',
        description: 'Investment plan for 1 bike - perfect for small investors',
        ficoSingleRent: 45,
        ficoRentToOwn: 55,
        ficoShareEv: 60,
      },
      {
        id: 'inv_demo_2',
        name: '5 Bike Plan',
        tier: 'Standard',
        minQuantity: 5,
        evBasePrice: 180000,
        minInvestment: 900000,
        maxInvestment: 5000000,
        durationMonths: 24,
        profitSharePercent: 50,
        lockInMonths: 6,
        earlyExitPenalty: 10,
        startDate: '2026-01-01',
        endDate: '2026-12-31',
        targetAmount: 5000000,
        status: 'active',
        description: 'Investment plan for 5 bikes - medium scale investment',
        ficoSingleRent: 45,
        ficoRentToOwn: 55,
        ficoShareEv: 60,
      },
    ],
    batteryInvestment: [
      {
        id: 'bat_inv_demo_1',
        name: 'Standard Battery Plan',
        tier: 'Economy',
        minQuantity: 10,
        batteryBasePrice: 15000,
        minInvestment: 150000,
        maxInvestment: 500000,
        durationMonths: 12,
        profitSharePercent: 40,
        lockInMonths: 3,
        earlyExitPenalty: 10,
        startDate: '2026-01-01',
        endDate: '2026-12-31',
        targetAmount: 500000,
        status: 'active',
        description: 'Investment plan for 10 batteries - entry level battery investment',
      },
      {
        id: 'bat_inv_demo_2',
        name: 'Premium Battery Plan',
        tier: 'Premium',
        minQuantity: 50,
        batteryBasePrice: 15000,
        minInvestment: 750000,
        maxInvestment: 2000000,
        durationMonths: 24,
        profitSharePercent: 50,
        lockInMonths: 6,
        earlyExitPenalty: 15,
        startDate: '2026-01-01',
        endDate: '2026-12-31',
        targetAmount: 2000000,
        status: 'active',
        description: 'Investment plan for 50 batteries - premium scale battery investment',
      },
    ],
    swapStation: [
      {
        id: 'ss_1',
        name: 'Basic Swap Station',
        batteryCount: 10,
        swapPrice: 50,
        monthlySubscription: 500,
        dailySubscription: 20,
        minBatteries: 1,
        maxBatteries: 5,
        profitSharePercent: 50,
        status: 'active',
        description: 'Basic swap station for small operators',
      },
      {
        id: 'ss_2',
        name: 'Premium Swap Station',
        batteryCount: 50,
        swapPrice: 45,
        monthlySubscription: 2000,
        dailySubscription: 80,
        minBatteries: 10,
        maxBatteries: 30,
        profitSharePercent: 55,
        status: 'active',
        description: 'Premium swap station for large operators',
      }
    ],
    riderRequest: [
      {
        id: 'rider_1',
        tier: 'Premium',
        name: 'Premium Rider Plan',
        minRiders: 10,
        maxRiders: 50,
        monthlySubscription: 3000,
        dailySubscription: 150,
        deposit: 5000,
        commissionPercent: 70,
        dailyRideTarget: 15,
        weeklyHoliday: 1,
        status: 'active',
        description: 'Premium rider plan for high volume operators',
      },
      {
        id: 'rider_2',
        tier: 'Standard',
        name: 'Standard Rider Plan',
        minRiders: 5,
        maxRiders: 20,
        monthlySubscription: 1500,
        dailySubscription: 80,
        deposit: 3000,
        commissionPercent: 60,
        dailyRideTarget: 10,
        weeklyHoliday: 1,
        status: 'active',
        description: 'Standard rider plan for medium operators',
      },
      {
        id: 'rider_3',
        tier: 'Economy',
        name: 'Economy Rider Plan',
        minRiders: 1,
        maxRiders: 10,
        monthlySubscription: 500,
        dailySubscription: 30,
        deposit: 1000,
        commissionPercent: 50,
        dailyRideTarget: 5,
        weeklyHoliday: 0,
        status: 'active',
        description: 'Economy rider plan for small operators',
      }
    ],
  },
};

export default function CompanySettingsPage() {
  const [settings, setSettings] = useState<CompanySettings>(initialSettings);
  
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const stored = localStorage.getItem('companySettings');
      if (stored) {
        try {
          setSettings(JSON.parse(stored));
        } catch (e) {
          console.error(e);
        }
      }
    }
  }, []);

  useEffect(() => {
    if (typeof window !== 'undefined' && settings !== initialSettings) {
      localStorage.setItem('companySettings', JSON.stringify(settings));
    }
  }, [settings]);
  const [activeTab, setActiveTab] = useState<'general' | 'branding' | 'social' | 'integration' | 'landing' | 'kyc' | 'parts' | 'companyPolicy' | 'plans' | 'investment' | 'batteryinvestment' | 'swapstation' | 'riderrequest' | 'templates'>('general');
  const [activeMasterTab, setActiveMasterTab] = useState<'investor' | 'merchant' | 'swapstation' | 'rentalType'>('investor');
  const [activeRentalTypeTab, setActiveRentalTypeTab] = useState<'single' | 'shared' | 'renttoown'>('single');
  const [saved, setSaved] = useState(false);
  const [activePlanTab, setActivePlanTab] = useState<'singleRent' | 'rentToOwn' | 'shareEv'>('singleRent');
  const [isDirty, setIsDirty] = useState(false);
  const [pendingTab, setPendingTab] = useState<typeof activeTab | null>(null);
  const [showUnsavedModal, setShowUnsavedModal] = useState(false);
  const [addDocType, setAddDocType] = useState<'investor' | 'merchant' | 'swapstation' | 'rental' | null>(null);
  const [newDocName, setNewDocName] = useState('');
  const [newDocDesc, setNewDocDesc] = useState('');
  const [activeInvestTab, setActiveInvestTab] = useState(0);
  const [editingPolicy, setEditingPolicy] = useState<{ tab: string; index: number } | null>(null);
  const [editPolicyName, setEditPolicyName] = useState('');
  const [editPolicyDesc, setEditPolicyDesc] = useState('');
  const [editPolicyDescHtml, setEditPolicyDescHtml] = useState('');
  const [editPolicyShowApp, setEditPolicyShowApp] = useState(true);
  const [editPolicyShowWeb, setEditPolicyShowWeb] = useState(true);
  const [showAddPolicy, setShowAddPolicy] = useState(false);
  const [newPolicyName, setNewPolicyName] = useState('');
  const [newPolicyDesc, setNewPolicyDesc] = useState('');
  const [newPolicyShowApp, setNewPolicyShowApp] = useState(true);
  const [newPolicyShowWeb, setNewPolicyShowWeb] = useState(true);

  // Bike Investment
  const [addInvestPlan, setAddInvestPlan] = useState(false);
  const [newInvestName, setNewInvestName] = useState('');
  const [newInvestTier, setNewInvestTier] = useState('Standard');
  const [newInvestStatus, setNewInvestStatus] = useState('active');
  const [newInvestTarget, setNewInvestTarget] = useState(1000000);
  const [newInvestStart, setNewInvestStart] = useState('2026-01-01');
  const [newInvestEnd, setNewInvestEnd] = useState('2026-12-31');
  const [newInvestMin, setNewInvestMin] = useState(10000);
  const [newInvestMax, setNewInvestMax] = useState(100000);
  const [newInvestDuration, setNewInvestDuration] = useState(12);
  const [newInvestLock, setNewInvestLock] = useState(3);
  const [newInvestPenalty, setNewInvestPenalty] = useState(10);
  const [newInvestProfitShare, setNewInvestProfitShare] = useState(50);
  const [newInvestFicoSingleRent, setNewInvestFicoSingleRent] = useState(45);
  const [newInvestFicoRentToOwn, setNewInvestFicoRentToOwn] = useState(55);
  const [newInvestFicoShareEv, setNewInvestFicoShareEv] = useState(60);
  const [newInvestDesc, setNewInvestDesc] = useState('');
  const [newInvestEvBasePrice, setNewInvestEvBasePrice] = useState(200000);
  const [newInvestMinQuantity, setNewInvestMinQuantity] = useState(1);

  // Battery Investment
  const [activeBatteryTab, setActiveBatteryTab] = useState(0);
  const [addBatteryPlan, setAddBatteryPlan] = useState(false);
  const [newBatteryName, setNewBatteryName] = useState('');
  const [newBatteryStatus, setNewBatteryStatus] = useState('active');
  const [newBatteryTarget, setNewBatteryTarget] = useState(1000000);
  const [newBatteryStart, setNewBatteryStart] = useState('2026-01-01');
  const [newBatteryEnd, setNewBatteryEnd] = useState('2026-12-31');
  const [newBatteryMin, setNewBatteryMin] = useState(150000);
  const [newBatteryMax, setNewBatteryMax] = useState(500000);
  const [newBatteryDuration, setNewBatteryDuration] = useState(12);
  const [newBatteryLock, setNewBatteryLock] = useState(3);
  const [newBatteryPenalty, setNewBatteryPenalty] = useState(10);
  const [newBatteryProfitShare, setNewBatteryProfitShare] = useState(40);
  const [newBatteryDesc, setNewBatteryDesc] = useState('');
  const [newBatteryBasePrice, setNewBatteryBasePrice] = useState(15000);
  const [newBatteryMinQuantity, setNewBatteryMinQuantity] = useState(10);

  const createInvestPlan = () => {
    if (newInvestName.trim() && typeof window !== 'undefined') {
      const newPlan = {
        id: 'inv_' + Date.now(),
        name: newInvestName,
        tier: newInvestTier,
        evBasePrice: newInvestEvBasePrice,
        minQuantity: newInvestMinQuantity,
        minInvestment: newInvestEvBasePrice * newInvestMinQuantity,
        maxInvestment: newInvestMax,
        durationMonths: newInvestDuration,
        profitSharePercent: newInvestProfitShare,
        lockInMonths: newInvestLock,
        earlyExitPenalty: newInvestPenalty,
        startDate: newInvestStart,
        endDate: newInvestEnd,
        targetAmount: newInvestTarget,
        status: newInvestStatus,
        description: newInvestDesc,
        ficoSingleRent: newInvestFicoSingleRent,
        ficoRentToOwn: newInvestFicoRentToOwn,
        ficoShareEv: newInvestFicoShareEv,
      };
      const updatedPlans = [...settings.plans.investment, newPlan];
      updateSettings({ ...settings, plans: { ...settings.plans, investment: updatedPlans } });
      setActiveInvestTab(updatedPlans.length - 1);
      setAddInvestPlan(false);
      setNewInvestName('');
    }
  };

  const createBatteryPlan = () => {
    if (newBatteryName.trim() && typeof window !== 'undefined') {
      const newPlan = {
        id: 'bat_inv_' + Date.now(),
        name: newBatteryName,
        tier: newBatteryMinQuantity >= 50 ? 'Premium' : 'Economy',
        batteryBasePrice: newBatteryBasePrice,
        minQuantity: newBatteryMinQuantity,
        minInvestment: newBatteryBasePrice * newBatteryMinQuantity,
        maxInvestment: newBatteryMax,
        durationMonths: newBatteryDuration,
        profitSharePercent: newBatteryProfitShare,
        lockInMonths: newBatteryLock,
        earlyExitPenalty: newBatteryPenalty,
        startDate: newBatteryStart,
        endDate: newBatteryEnd,
        targetAmount: newBatteryTarget,
        status: newBatteryStatus,
        description: newBatteryDesc,
      };
      const updatedPlans = [...(settings.plans.batteryInvestment || []), newPlan];
      updateSettings({ ...settings, plans: { ...settings.plans, batteryInvestment: updatedPlans } });
      setActiveBatteryTab(updatedPlans.length - 1);
      setAddBatteryPlan(false);
      setNewBatteryName('');
    }
  };


  const [activeSwapTab, setActiveSwapTab] = useState(0);
  const [addSwapStationPlan, setAddSwapStationPlan] = useState(false);
  const [newSwapName, setNewSwapName] = useState('');
  const [newSwapStatus, setNewSwapStatus] = useState('active');
  const [newSwapBatteryCount, setNewSwapBatteryCount] = useState(10);
  const [newSwapPrice, setNewSwapPrice] = useState(50);
  const [newSwapMonthly, setNewSwapMonthly] = useState(500);
  const [newSwapDaily, setNewSwapDaily] = useState(20);
  const [newSwapMin, setNewSwapMin] = useState(1);
  const [newSwapMax, setNewSwapMax] = useState(5);
  const [newSwapProfit, setNewSwapProfit] = useState(50);
  const [newSwapDesc, setNewSwapDesc] = useState('');

  const createSwapStationPlan = () => {
    if (newSwapName.trim() && typeof window !== 'undefined') {
      const newPlan = {
        id: 'ss_' + Date.now(),
        name: newSwapName,
        batteryCount: newSwapBatteryCount,
        swapPrice: newSwapPrice,
        monthlySubscription: newSwapMonthly,
        dailySubscription: newSwapDaily,
        minBatteries: newSwapMin,
        maxBatteries: newSwapMax,
        profitSharePercent: newSwapProfit,
        status: newSwapStatus,
        description: newSwapDesc
      };
      const updatedPlans = [...settings.plans.swapStation, newPlan];
      updateSettings({ ...settings, plans: { ...settings.plans, swapStation: updatedPlans } });
      setActiveSwapTab(updatedPlans.length - 1);
      setAddSwapStationPlan(false);
      setNewSwapName('');
    }
  };
  const [activeRiderTab, setActiveRiderTab] = useState(0);
  const [addRiderPlan, setAddRiderPlan] = useState(false);
  const [newRiderName, setNewRiderName] = useState('');
  const [newRiderTier, setNewRiderTier] = useState('Standard');
  const [newRiderStatus, setNewRiderStatus] = useState('active');
  const [newRiderMin, setNewRiderMin] = useState(1);
  const [newRiderMax, setNewRiderMax] = useState(10);
  const [newRiderMonthly, setNewRiderMonthly] = useState(500);
  const [newRiderDaily, setNewRiderDaily] = useState(30);
  const [newRiderDeposit, setNewRiderDeposit] = useState(1000);
  const [newRiderCommission, setNewRiderCommission] = useState(50);
  const [newRiderTarget, setNewRiderTarget] = useState(5);
  const [newRiderHoliday, setNewRiderHoliday] = useState(0);
  const [newRiderDesc, setNewRiderDesc] = useState('');
  const createRiderPlan = () => {
    if (newRiderName.trim() && typeof window !== 'undefined') {
      const newPlan = {
        id: 'rider_' + Date.now(),
        name: newRiderName,
        tier: newRiderTier,
        minRiders: newRiderMin,
        maxRiders: newRiderMax,
        monthlySubscription: newRiderMonthly,
        dailySubscription: newRiderDaily,
        deposit: newRiderDeposit,
        commissionPercent: newRiderCommission,
        dailyRideTarget: newRiderTarget,
        weeklyHoliday: newRiderHoliday,
        status: newRiderStatus,
        description: newRiderDesc
      };
      const updatedPlans = [...settings.plans.riderRequest, newPlan];
      updateSettings({ ...settings, plans: { ...settings.plans, riderRequest: updatedPlans } });
      setActiveRiderTab(updatedPlans.length - 1);
      setAddRiderPlan(false);
      setNewRiderName('');
    }
  };
  const handleSave = () => {
    setSaved(true);
    setIsDirty(false);
    setTimeout(() => setSaved(false), 2000);
  };

  const handleTabChange = (tab: typeof activeTab) => {
    if (isDirty) {
      setPendingTab(tab);
      setShowUnsavedModal(true);
    } else {
      setActiveTab(tab);
    }
  };

  const updateSettings = (updater: React.SetStateAction<CompanySettings>) => {
    setSettings(updater);
    setIsDirty(true);
  };

  const addNewPlan = (type: 'singleRent' | 'rentToOwn' | 'shareEv') => {
    const newId = `${type}-${Date.now()}`;
    const defaultPlan = type === 'singleRent' ? {
      id: newId,
      name: '',
      evModels: [],
      contractMonths: [1, 3, 6],
      dailyRent: 300,
      dailyRentPenalty1: 400,
      dailyRentPenalty2: 800,
      dailyRentPenalty3: 4000,
      deposit: 20000,
      weeklySubscription: 2100,
      weeklyPenalty1: 2600,
      weeklyPenalty2: 5200,
      weeklyPenalty3: 12000,
      monthlySubscription: 9000,
      monthlyPenalty1: 11000,
      monthlyPenalty2: 22000,
      monthlyPenalty3: 40000,
      ficoSharePercent: 45,
      freeServiceConditions: [],
      description: '',
    } : type === 'rentToOwn' ? {
      id: newId,
      name: '',
      evModels: [],
      contractMonths: [12, 18, 24],
      dailyRent: 250,
      dailyRentPenalty1: 350,
      dailyRentPenalty2: 700,
      dailyRentPenalty3: 3500,
      deposit: 18000,
      weeklySubscription: 1750,
      weeklyPenalty1: 2200,
      weeklyPenalty2: 4400,
      weeklyPenalty3: 10000,
      monthlySubscription: 7000,
      monthlyPenalty1: 9000,
      monthlyPenalty2: 18000,
      monthlyPenalty3: 30000,
      durationMonths: 18,
      evPrice: 120000,
      totalPayment: 135000,
      profit: 15000,
      ficoRentSharePercent: 45,
      ficoProfitSharePercent: 45,
      freeServiceConditions: [],
      description: '',
    } : {
      id: newId,
      name: '',
      evModels: [],
      contractMonths: [1, 3, 6],
      dailyRentEach: 200,
      dailyRentPenalty1: 250,
      dailyRentPenalty2: 500,
      dailyRentPenalty3: 2500,
      totalDailyRent: 400,
      depositEach: 15000,
      depositPenalty1: 18000,
      depositPenalty2: 25000,
      depositPenalty3: 40000,
      totalDeposit: 30000,
      weeklySubscriptionEach: 1400,
      weeklyPenalty1: 1800,
      weeklyPenalty2: 3500,
      weeklyPenalty3: 8000,
      totalWeeklySubscription: 2800,
      monthlySubscriptionEach: 5600,
      monthlyPenalty1: 7000,
      monthlyPenalty2: 14000,
      monthlyPenalty3: 25000,
      totalMonthlySubscription: 11200,
      ficoSharePercent: 45,
      freeServiceConditions: [],
      description: '',
    };
    if (type === 'singleRent') {
      updateSettings({ ...settings, plans: { ...settings.plans, singleRent: [...settings.plans.singleRent, defaultPlan as typeof settings.plans.singleRent[number]] } });
    } else if (type === 'rentToOwn') {
      updateSettings({ ...settings, plans: { ...settings.plans, rentToOwn: [...settings.plans.rentToOwn, defaultPlan as typeof settings.plans.rentToOwn[number]] } });
    } else {
      updateSettings({ ...settings, plans: { ...settings.plans, shareEv: [...settings.plans.shareEv, defaultPlan as typeof settings.plans.shareEv[number]] } });
    }
    return newId;
  };

  const addPolicyRule = (tab: 'investor' | 'merchant' | 'swapstation') => {
    if (!newPolicyName.trim()) return;
    const newRule = { title: newPolicyName, description: newPolicyDesc || '<p></p>', showApp: newPolicyShowApp, showWeb: newPolicyShowWeb };
    if (tab === 'investor') {
      updateSettings({ ...settings, companyPolicy: { ...settings.companyPolicy, investor: [...settings.companyPolicy.investor, newRule as typeof settings.companyPolicy.investor[number]] } });
    } else if (tab === 'merchant') {
      updateSettings({ ...settings, companyPolicy: { ...settings.companyPolicy, merchant: [...settings.companyPolicy.merchant, newRule as typeof settings.companyPolicy.merchant[number]] } });
    } else if (tab === 'swapstation') {
      updateSettings({ ...settings, companyPolicy: { ...settings.companyPolicy, swapStation: [...settings.companyPolicy.swapStation, newRule as typeof settings.companyPolicy.swapStation[number]] } });
    }
    setNewPolicyName('');
    setNewPolicyDesc('');
    setShowAddPolicy(false);
  };

  const deletePolicyRule = (tab: 'investor' | 'merchant' | 'swapstation', index: number) => {
    if (tab === 'investor') {
      const newRules = settings.companyPolicy.investor.filter((_, i) => i !== index);
      updateSettings({ ...settings, companyPolicy: { ...settings.companyPolicy, investor: newRules } });
    } else if (tab === 'merchant') {
      const newRules = settings.companyPolicy.merchant.filter((_, i) => i !== index);
      updateSettings({ ...settings, companyPolicy: { ...settings.companyPolicy, merchant: newRules } });
    } else if (tab === 'swapstation') {
      const newRules = settings.companyPolicy.swapStation.filter((_, i) => i !== index);
      updateSettings({ ...settings, companyPolicy: { ...settings.companyPolicy, swapStation: newRules } });
    }
  };

  const updatePolicyRule = (tab: 'investor' | 'merchant' | 'swapstation', index: number) => {
    const newDesc = editPolicyDescHtml || editPolicyDesc;
    const updated = { title: editPolicyName, description: newDesc, showApp: editPolicyShowApp, showWeb: editPolicyShowWeb };
    if (tab === 'investor') {
      const newRules = [...settings.companyPolicy.investor];
      newRules[index] = updated as typeof settings.companyPolicy.investor[number];
      updateSettings({ ...settings, companyPolicy: { ...settings.companyPolicy, investor: newRules } });
    } else if (tab === 'merchant') {
      const newRules = [...settings.companyPolicy.merchant];
      newRules[index] = updated as typeof settings.companyPolicy.merchant[number];
      updateSettings({ ...settings, companyPolicy: { ...settings.companyPolicy, merchant: newRules } });
    } else if (tab === 'swapstation') {
      const newRules = [...settings.companyPolicy.swapStation];
      newRules[index] = updated as typeof settings.companyPolicy.swapStation[number];
      updateSettings({ ...settings, companyPolicy: { ...settings.companyPolicy, swapStation: newRules } });
    }
    setEditingPolicy(null);
  };

  const tabs = [
    { id: 'general', label: 'General', icon: Settings },
    { id: 'branding', label: 'Branding', icon: Palette },
    { id: 'social', label: 'Social Media', icon: Link2 },
    { id: 'integration', label: 'Integrations', icon: Mail },
    { id: 'landing', label: 'Landing Page', icon: Monitor },
    { id: 'companyPolicy', label: "Company's Policy", icon: FileCheck },
    { id: 'kyc', label: 'KYC Documents', icon: Package },

    { id: 'plans', label: 'Plan Selection', icon: Package },
    { id: 'investment', label: 'EV Investment Plan', icon: DollarSign },
    { id: 'batteryinvestment', label: 'Battery Investment Plan', icon: Battery },
    { id: 'swapstation', label: 'Swap Station Plan (P3)', icon: Zap },
    { id: 'riderrequest', label: 'Rider Request Plan (P2)', icon: Users },
    { id: 'parts', label: 'EV Parts', icon: Package },

    { id: 'templates', label: 'Email & SMS Templates', icon: FileText },
  ];

  return (
    <>
      {showUnsavedModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-sm overflow-hidden">
            <div className="p-6 text-center">
              <div className="w-14 h-14 bg-amber-50 rounded-full flex items-center justify-center mx-auto mb-4">
                <Save className="w-7 h-7 text-amber-500" />
              </div>
              <h3 className="text-lg font-bold text-slate-800 mb-1">Unsaved Changes</h3>
              <p className="text-sm text-slate-500">You have unsaved changes. What would you like to do?</p>
            </div>
            <div className="p-4 bg-slate-50 flex gap-3">
              <button onClick={() => { setShowUnsavedModal(false); setPendingTab(null); }} className="flex-1 py-2.5 bg-white border border-slate-200 text-slate-600 rounded-lg text-sm font-medium hover:bg-slate-100 transition-colors">Keep Editing</button>
              <button onClick={() => { setIsDirty(false); setShowUnsavedModal(false); setActiveTab(pendingTab!); setPendingTab(null); }} className="flex-1 py-2.5 bg-slate-600 text-white rounded-lg text-sm font-medium hover:bg-slate-700 transition-colors">Discard</button>
              <button onClick={() => { handleSave(); setShowUnsavedModal(false); setActiveTab(pendingTab!); setPendingTab(null); }} className="flex-1 py-2.5 bg-accent text-white rounded-lg text-sm font-medium hover:bg-accent-dark transition-colors">Save & Switch</button>
            </div>
          </div>
        </div>
      )}
      <div className="p-4 lg:p-6">
        <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-6">
          <div>
            <h1 className="text-2xl lg:text-3xl font-extrabold text-slate-800">Company Settings</h1>
            <p className="text-sm text-slate-500 mt-1">Manage your company information and configurations</p>
          </div>
          {/* <button
          onClick={handleSave}
          className="py-2.5 px-4 bg-accent text-white rounded-lg font-semibold text-sm hover:bg-accent-dark transition-colors flex items-center gap-2"
        >
          <Save className="w-4 h-4" /> Save Changes
        </button> */}
        </div>

        {saved && (
          <div className="mb-4 p-3 bg-green-100 text-green-700 rounded-lg text-sm">
            Settings saved successfully!
          </div>
        )}

        <div className="grid lg:grid-cols-4 gap-6">
          <div className="lg:col-span-1 bg-white rounded-xl shadow-sm border border-slate-100 p-2">
            <nav className="space-y-1">
              {tabs.map(tab => (
                <button
                  key={tab.id}
                  onClick={() => handleTabChange(tab.id as typeof activeTab)}
                  className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${activeTab === tab.id
                    ? 'bg-accent text-white'
                    : 'text-slate-600 hover:bg-slate-50'
                    }`}
                >
                  <tab.icon className="w-4 h-4" />
                  {tab.label}
                </button>
              ))}
            </nav>
          </div>

          <div className="lg:col-span-3 bg-white rounded-xl shadow-sm border border-slate-100">
            {activeTab === 'general' && (
              <GeneralSettings settings={settings} setSettings={updateSettings} />
            )}

            {activeTab === 'branding' && (
              <BrandingSettings settings={settings} setSettings={updateSettings} />
            )}

            {activeTab === 'social' && (
              <SocialSettings settings={settings} setSettings={updateSettings} />
            )}

            {activeTab === 'integration' && (
              <IntegrationSettings settings={settings} setSettings={updateSettings} />
            )}

            {activeTab === 'landing' && (
              <LandingSettings settings={settings} setSettings={updateSettings} />
            )}

            {activeTab === 'kyc' && (
              <KycSettings
                settings={settings}
                setSettings={updateSettings}
                activeMasterTab={activeMasterTab}
                setActiveMasterTab={setActiveMasterTab}
                addDocType={addDocType}
                setAddDocType={setAddDocType}
                newDocName={newDocName}
                setNewDocName={setNewDocName}
                newDocDesc={newDocDesc}
                setNewDocDesc={setNewDocDesc}
              />
            )}

            {activeTab === 'parts' && (
              <PartsSettings
                settings={settings}
                setSettings={updateSettings}
                showAddPolicy={showAddPolicy}
                setShowAddPolicy={setShowAddPolicy}
                newPolicyName={newPolicyName}
                setNewPolicyName={setNewPolicyName}
                newPolicyDesc={newPolicyDesc}
                setNewPolicyDesc={setNewPolicyDesc}
                editPolicyDescHtml={editPolicyDescHtml}
                setEditPolicyDescHtml={setEditPolicyDescHtml}
                editingPolicy={editingPolicy}
                setEditingPolicy={setEditingPolicy}
                editPolicyName={editPolicyName}
                setEditPolicyName={setEditPolicyName}
                editPolicyDesc={editPolicyDesc}
                setEditPolicyDesc={setEditPolicyDesc}
              />
            )}

            {activeTab === 'companyPolicy' && (
              <CompanyPolicySettings
                settings={settings}
                setSettings={updateSettings}
                activeMasterTab={activeMasterTab}
                setActiveMasterTab={setActiveMasterTab}
                activeRentalTypeTab={activeRentalTypeTab}
                setActiveRentalTypeTab={setActiveRentalTypeTab}
                editingPolicy={editingPolicy}
                setEditingPolicy={setEditingPolicy}
                editPolicyName={editPolicyName}
                setEditPolicyName={setEditPolicyName}
                editPolicyDesc={editPolicyDesc}
                setEditPolicyDesc={setEditPolicyDesc}
                editPolicyDescHtml={editPolicyDescHtml}
                setEditPolicyDescHtml={setEditPolicyDescHtml}
                showAddPolicy={showAddPolicy}
                setShowAddPolicy={setShowAddPolicy}
                newPolicyName={newPolicyName}
                setNewPolicyName={setNewPolicyName}
                newPolicyDesc={newPolicyDesc}
                setNewPolicyDesc={setNewPolicyDesc}
                newPolicyShowApp={newPolicyShowApp}
                setNewPolicyShowApp={setNewPolicyShowApp}
                newPolicyShowWeb={newPolicyShowWeb}
                setNewPolicyShowWeb={setNewPolicyShowWeb}
                editPolicyShowApp={editPolicyShowApp}
                setEditPolicyShowApp={setEditPolicyShowApp}
                editPolicyShowWeb={editPolicyShowWeb}
                setEditPolicyShowWeb={setEditPolicyShowWeb}
              />
            )}

            {activeTab === 'plans' && (
              <PlanSelection
                settings={settings}
                setSettings={updateSettings}
                activePlanTab={activePlanTab}
                setActivePlanTab={setActivePlanTab}
                handleSave={handleSave}
                addNewPlan={addNewPlan}
              />
            )}

            {activeTab === 'investment' && (
              <InvestmentSettings
                settings={settings} setSettings={setSettings}
                activeInvestTab={activeInvestTab} setActiveInvestTab={setActiveInvestTab}
                addInvestPlan={addInvestPlan} setAddInvestPlan={setAddInvestPlan}
                newInvestName={newInvestName} setNewInvestName={setNewInvestName}
                newInvestStatus={newInvestStatus} setNewInvestStatus={setNewInvestStatus}
                newInvestTarget={newInvestTarget} setNewInvestTarget={setNewInvestTarget}
                newInvestStart={newInvestStart} setNewInvestStart={setNewInvestStart}
                newInvestEnd={newInvestEnd} setNewInvestEnd={setNewInvestEnd}
                newInvestMin={newInvestMin} setNewInvestMin={setNewInvestMin}
                newInvestMax={newInvestMax} setNewInvestMax={setNewInvestMax}
                newInvestDuration={newInvestDuration} setNewInvestDuration={setNewInvestDuration}
                newInvestLock={newInvestLock} setNewInvestLock={setNewInvestLock}
                newInvestPenalty={newInvestPenalty} setNewInvestPenalty={setNewInvestPenalty}
                newInvestFicoSingleRent={newInvestFicoSingleRent} setNewInvestFicoSingleRent={setNewInvestFicoSingleRent}
                newInvestFicoRentToOwn={newInvestFicoRentToOwn} setNewInvestFicoRentToOwn={setNewInvestFicoRentToOwn}
                newInvestFicoShareEv={newInvestFicoShareEv} setNewInvestFicoShareEv={setNewInvestFicoShareEv}
                newInvestDesc={newInvestDesc} setNewInvestDesc={setNewInvestDesc}
                newInvestEvBasePrice={newInvestEvBasePrice} setNewInvestEvBasePrice={setNewInvestEvBasePrice}
                newInvestMinQuantity={newInvestMinQuantity} setNewInvestMinQuantity={setNewInvestMinQuantity}
                createInvestPlan={createInvestPlan} handleSave={handleSave}
              />
            )}

            {activeTab === 'batteryinvestment' && (
              <BatteryInvestmentSettings
                settings={settings} setSettings={setSettings}
                activeBatteryTab={activeBatteryTab} setActiveBatteryTab={setActiveBatteryTab}
                addBatteryPlan={addBatteryPlan} setAddBatteryPlan={setAddBatteryPlan}
                newBatteryName={newBatteryName} setNewBatteryName={setNewBatteryName}
                newBatteryStatus={newBatteryStatus} setNewBatteryStatus={setNewBatteryStatus}
                newBatteryTarget={newBatteryTarget} setNewBatteryTarget={setNewBatteryTarget}
                newBatteryStart={newBatteryStart} setNewBatteryStart={setNewBatteryStart}
                newBatteryEnd={newBatteryEnd} setNewBatteryEnd={setNewBatteryEnd}
                newBatteryMin={newBatteryMin} setNewBatteryMin={setNewBatteryMin}
                newBatteryMax={newBatteryMax} setNewBatteryMax={setNewBatteryMax}
                newBatteryDuration={newBatteryDuration} setNewBatteryDuration={setNewBatteryDuration}
                newBatteryLock={newBatteryLock} setNewBatteryLock={setNewBatteryLock}
                newBatteryPenalty={newBatteryPenalty} setNewBatteryPenalty={setNewBatteryPenalty}
                newBatteryProfitShare={newBatteryProfitShare} setNewBatteryProfitShare={setNewBatteryProfitShare}
                newBatteryDesc={newBatteryDesc} setNewBatteryDesc={setNewBatteryDesc}
                newBatteryBasePrice={newBatteryBasePrice} setNewBatteryBasePrice={setNewBatteryBasePrice}
                newBatteryMinQuantity={newBatteryMinQuantity} setNewBatteryMinQuantity={setNewBatteryMinQuantity}
                createBatteryPlan={createBatteryPlan} handleSave={handleSave}
              />
            )}

            {
              activeTab === 'swapstation' && (
                <SwapStationSettings
                  settings={settings} setSettings={setSettings}
                  activeSwapTab={activeSwapTab} setActiveSwapTab={setActiveSwapTab}
                  addSwapStationPlan={addSwapStationPlan} setAddSwapStationPlan={setAddSwapStationPlan}
                  newSwapName={newSwapName} setNewSwapName={setNewSwapName}
                  newSwapStatus={newSwapStatus} setNewSwapStatus={setNewSwapStatus}
                  newSwapBatteryCount={newSwapBatteryCount} setNewSwapBatteryCount={setNewSwapBatteryCount}
                  newSwapPrice={newSwapPrice} setNewSwapPrice={setNewSwapPrice}
                  newSwapMonthly={newSwapMonthly} setNewSwapMonthly={setNewSwapMonthly}
                  newSwapDaily={newSwapDaily} setNewSwapDaily={setNewSwapDaily}
                  newSwapMin={newSwapMin} setNewSwapMin={setNewSwapMin}
                  newSwapMax={newSwapMax} setNewSwapMax={setNewSwapMax}
                  newSwapProfit={newSwapProfit} setNewSwapProfit={setNewSwapProfit}
                  newSwapDesc={newSwapDesc} setNewSwapDesc={setNewSwapDesc}
                  createSwapStationPlan={createSwapStationPlan} handleSave={handleSave}
                />
              )}

            {
              activeTab === 'riderrequest' && (
                <RiderRequestSettings
                  settings={settings} setSettings={setSettings}
                  activeRiderTab={activeRiderTab} setActiveRiderTab={setActiveRiderTab}
                  addRiderPlan={addRiderPlan} setAddRiderPlan={setAddRiderPlan}
                  newRiderName={newRiderName} setNewRiderName={setNewRiderName}
                  newRiderTier={newRiderTier} setNewRiderTier={setNewRiderTier}
                  newRiderStatus={newRiderStatus} setNewRiderStatus={setNewRiderStatus}
                  newRiderMin={newRiderMin} setNewRiderMin={setNewRiderMin}
                  newRiderMax={newRiderMax} setNewRiderMax={setNewRiderMax}
                  newRiderMonthly={newRiderMonthly} setNewRiderMonthly={setNewRiderMonthly}
                  newRiderDaily={newRiderDaily} setNewRiderDaily={setNewRiderDaily}
                  newRiderDeposit={newRiderDeposit} setNewRiderDeposit={setNewRiderDeposit}
                  newRiderCommission={newRiderCommission} setNewRiderCommission={setNewRiderCommission}
                  newRiderTarget={newRiderTarget} setNewRiderTarget={setNewRiderTarget}
                  newRiderHoliday={newRiderHoliday} setNewRiderHoliday={setNewRiderHoliday}
                  newRiderDesc={newRiderDesc} setNewRiderDesc={setNewRiderDesc}
                  createRiderPlan={createRiderPlan} handleSave={handleSave}
                />
              )}

            {activeTab === 'templates' && (
              <EmailSMSTemplates settings={settings} setSettings={updateSettings} />
            )}

          </div >
        </div >


      </div >
    </>
  );
}