'use client';

import React from 'react';
import { t } from '@/i18n/locales';
import { useApi } from '@/lib/use-api';

/**
 * Tax Compliance Management - 税务合规管理
 */

interface TaxData {
  stats: { label: string; value: string; color: string }[];
  obligations: { jurisdiction: string; taxType: string; period: string; amount: number; paid: number; status: string; dueDate: string }[];
  typeBreakdown: { type: string; federal: string; state: string; total: string; percentage: number }[];
  irsFilings: { form: string; description: string; taxYear: string; deadline: string; status: string; filedDate: string }[];
  deadlines: { date: string; event: string; done: boolean }[];
}

const loadingBox: React.CSSProperties = {
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  padding: 40, color: 'var(--color-text-tertiary)', font: 'var(--text-body)',
};

const getPaymentStatusStyle = (status: string) => {
  switch (status) {
    case 'paid': return { background: 'var(--color-success-light)', color: 'var(--color-success)' };
    case 'partial': return { background: 'var(--color-warning-light)', color: 'var(--color-warning)' };
    case 'unpaid': return { background: 'var(--color-error-light)', color: 'var(--color-error)' };
    default: return { background: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)' };
  }
};

const getPaymentStatusLabel = (status: string) => {
  const map: Record<string, () => string> = {
    paid: () => t('tax_status_paid'),
    partial: () => t('tax_status_partial'),
    unpaid: () => t('tax_status_unpaid'),
  };
  return map[status]?.() ?? status;
};

const getFilingStatusStyle = (status: string) => {
  switch (status) {
    case 'submitted': return { background: 'var(--color-success-light)', color: 'var(--color-success)' };
    case 'preparing': return { background: 'var(--color-warning-light)', color: 'var(--color-warning)' };
    case 'on_demand': return { background: 'var(--color-info-light)', color: 'var(--color-info)' };
    case 'overdue': return { background: 'var(--color-error-light)', color: 'var(--color-error)' };
    default: return { background: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)' };
  }
};

const getFilingStatusLabel = (status: string) => {
  const map: Record<string, () => string> = {
    submitted: () => t('tax_filing_submitted'),
    preparing: () => t('tax_filing_preparing'),
    on_demand: () => t('tax_filing_on_demand'),
    overdue: () => t('tax_filing_overdue'),
  };
  return map[status]?.() ?? status;
};

export const TaxCompliancePage: React.FC = () => {
  const { data, isLoading, error } = useApi<TaxData>('/api/v1/admin/compliance/tax');

  if (error) return <div style={loadingBox}>Error: {error.message}</div>;
  if (isLoading) return <div style={loadingBox}>Loading...</div>;

  const taxStats = data?.stats ?? [];
  const taxObligations = data?.obligations ?? [];
  const taxTypeBreakdown = data?.typeBreakdown ?? [];
  const irsFilings = data?.irsFilings ?? [];
  const taxDeadlines = data?.deadlines ?? [];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h1 style={{ font: 'var(--text-h1)', color: 'var(--color-text-primary)' }}>{t('tax_title')}</h1>
        <button style={{
          padding: '8px 16px', border: 'none', borderRadius: 'var(--radius-full)',
          background: 'var(--color-primary)', color: 'white', cursor: 'pointer', font: 'var(--text-label-sm)',
        }}>{t('tax_export_report')}</button>
      </div>

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        {taxStats.map(s => (
          <div key={s.label} style={{
            background: 'var(--color-surface)', borderRadius: 'var(--radius-md)',
            border: '1px solid var(--color-border-light)', padding: 20,
          }}>
            <div style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', marginBottom: 8 }}>{s.label}</div>
            <div style={{ font: 'var(--text-h1)', color: s.color }}>{s.value}</div>
          </div>
        ))}
      </div>

      {/* Tax Obligations */}
      <div style={{
        background: 'var(--color-surface)', borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-border-light)', overflow: 'hidden', marginBottom: 24,
      }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--color-border-light)' }}>
          <h2 style={{ font: 'var(--text-h2)', color: 'var(--color-text-primary)' }}>{t('tax_obligations')}</h2>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: 'var(--color-gray-50)' }}>
              {[t('tax_th_jurisdiction'), t('tax_th_type'), t('tax_th_period'), t('tax_th_payable'), t('tax_th_paid'), t('tax_th_deadline'), t('tax_th_status')].map(h => (
                <th key={h} style={{ font: 'var(--text-label-sm)', color: 'var(--color-text-tertiary)', padding: '10px 14px', textAlign: 'left' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {taxObligations.map((tax, i) => (
              <tr key={i} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                <td style={{ padding: '10px 14px' }}>
                  <span style={{
                    padding: '2px 8px', borderRadius: 'var(--radius-full)',
                    background: tax.jurisdiction === 'Federal' ? 'var(--color-primary-light)' : 'var(--color-info-light)',
                    color: tax.jurisdiction === 'Federal' ? 'var(--color-primary)' : 'var(--color-info)',
                    font: 'var(--text-caption)', fontWeight: 600,
                  }}>{tax.jurisdiction}</span>
                </td>
                <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-primary)' }}>{tax.taxType}</td>
                <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-tertiary)' }}>{tax.period}</td>
                <td style={{ font: 'var(--text-label-sm)', padding: '10px 14px', color: 'var(--color-text-primary)' }}>${tax.amount?.toLocaleString()}</td>
                <td style={{ font: 'var(--text-label-sm)', padding: '10px 14px', color: 'var(--color-success)' }}>${tax.paid?.toLocaleString()}</td>
                <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-tertiary)' }}>{tax.dueDate}</td>
                <td style={{ padding: '10px 14px' }}>
                  <span style={{
                    padding: '2px 8px', borderRadius: 'var(--radius-full)', font: 'var(--text-caption)', fontWeight: 600,
                    ...getPaymentStatusStyle(tax.status),
                  }}>{getPaymentStatusLabel(tax.status)}</span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Tax Type Breakdown + Tax Calendar */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, marginBottom: 24 }}>
        <div style={{
          background: 'var(--color-surface)', borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)', overflow: 'hidden',
        }}>
          <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--color-border-light)' }}>
            <h2 style={{ font: 'var(--text-h2)', color: 'var(--color-text-primary)' }}>{t('tax_type_breakdown')}</h2>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ background: 'var(--color-gray-50)' }}>
                {[t('tax_th_tax_type'), t('tax_th_federal'), t('tax_th_state'), t('tax_th_total'), t('tax_th_percentage')].map(h => (
                  <th key={h} style={{ font: 'var(--text-label-sm)', color: 'var(--color-text-tertiary)', padding: '10px 14px', textAlign: 'left' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {taxTypeBreakdown.map((row, i) => (
                <tr key={i} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-primary)' }}>{row.type}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-secondary)' }}>{row.federal}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-secondary)' }}>{row.state}</td>
                  <td style={{ font: 'var(--text-label-sm)', padding: '10px 14px', color: 'var(--color-text-primary)' }}>{row.total}</td>
                  <td style={{ padding: '10px 14px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div style={{ flex: 1, height: 6, background: 'var(--color-gray-100)', borderRadius: 'var(--radius-full)', overflow: 'hidden' }}>
                        <div style={{ width: `${row.percentage}%`, height: '100%', background: 'var(--color-primary)', borderRadius: 'var(--radius-full)' }} />
                      </div>
                      <span style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)', minWidth: 40, textAlign: 'right' }}>{row.percentage}%</span>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div style={{ background: 'var(--color-surface)', borderRadius: 'var(--radius-md)', border: '1px solid var(--color-border-light)', padding: 20 }}>
          <h2 style={{ font: 'var(--text-h2)', marginBottom: 16 }}>{t('tax_calendar')}</h2>
          {taxDeadlines.map((evt, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'flex-start', padding: '10px 0', borderBottom: '1px solid var(--color-border-light)' }}>
              <div style={{
                width: 20, height: 20, borderRadius: '50%', marginRight: 12, marginTop: 2, flexShrink: 0,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                background: evt.done ? 'var(--color-success)' : 'var(--color-error)',
                color: 'white', fontSize: 10,
              }}>
                {evt.done ? '✓' : '!'}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ font: 'var(--text-body)', color: 'var(--color-text-primary)' }}>{evt.event}</div>
                <div style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)', marginTop: 2 }}>{evt.date}</div>
              </div>
              <span style={{
                font: 'var(--text-caption)',
                color: evt.done ? 'var(--color-success)' : 'var(--color-error)',
              }}>
                {evt.done ? t('tax_status_done') : t('tax_status_pending')}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* IRS Filing Tracker */}
      <div style={{
        background: 'var(--color-surface)', borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-border-light)', overflow: 'hidden',
      }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--color-border-light)' }}>
          <h2 style={{ font: 'var(--text-h2)', color: 'var(--color-text-primary)' }}>{t('tax_irs_tracker')}</h2>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: 'var(--color-gray-50)' }}>
              {[t('tax_th_form'), t('tax_th_description'), t('tax_th_tax_year'), t('tax_th_deadline'), t('tax_th_filed_date'), t('tax_th_status')].map(h => (
                <th key={h} style={{ font: 'var(--text-label-sm)', color: 'var(--color-text-tertiary)', padding: '10px 14px', textAlign: 'left' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {irsFilings.map((f, i) => (
              <tr key={i} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                <td style={{ padding: '10px 14px' }}>
                  <span style={{
                    padding: '2px 10px', borderRadius: 'var(--radius-full)',
                    background: 'var(--color-primary-light)', color: 'var(--color-primary)',
                    font: 'var(--text-label-sm)', fontWeight: 600,
                  }}>{f.form}</span>
                </td>
                <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-primary)' }}>{f.description}</td>
                <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-tertiary)' }}>{f.taxYear}</td>
                <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-secondary)' }}>{f.deadline}</td>
                <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-tertiary)' }}>{f.filedDate}</td>
                <td style={{ padding: '10px 14px' }}>
                  <span style={{
                    padding: '2px 8px', borderRadius: 'var(--radius-full)', font: 'var(--text-caption)', fontWeight: 600,
                    ...getFilingStatusStyle(f.status),
                  }}>{getFilingStatusLabel(f.status)}</span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};
