import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../l10n/app_strings.dart';
import '../models/klt_models.dart';
import '../services/ai_handoff_service.dart';
import '../services/project_engine.dart';
import '../services/report_service.dart';
import '../services/visualization_service.dart';
import '../widgets/klt_visual_painters.dart';
import '../widgets/metric_card.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final TextEditingController _controller = TextEditingController(text: _demoProjectJson);
  String _lang = 'ru';
  KltAnalysis? _analysis;
  String? _error;

  AppStrings get s => AppStrings(_lang);

  @override
  void initState() {
    super.initState();
    _runAnalysis();
  }

  void _runAnalysis() {
    try {
      final result = ProjectEngine().analyzeJson(_controller.text);
      setState(() {
        _analysis = result;
        _error = null;
      });
    } catch (e) {
      setState(() => _error = e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 5,
      child: Scaffold(
        appBar: AppBar(
          title: Text(s.t('title')),
          bottom: TabBar(
            isScrollable: true,
            tabs: [
              Tab(text: s.t('dashboard')),
              Tab(text: s.t('input')),
              Tab(text: s.t('schemes')),
              Tab(text: s.t('report')),
              Tab(text: s.t('method')),
            ],
          ),
          actions: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 12),
              child: DropdownButtonHideUnderline(
                child: DropdownButton<String>(
                  value: _lang,
                  onChanged: (value) => setState(() => _lang = value ?? 'ru'),
                  items: const [
                    DropdownMenuItem(value: 'ru', child: Text('RU')),
                    DropdownMenuItem(value: 'en', child: Text('EN')),
                    DropdownMenuItem(value: 'zh', child: Text('ZH')),
                  ],
                ),
              ),
            ),
          ],
        ),
        body: TabBarView(
          children: [
            _dashboard(),
            _input(),
            _visuals(),
            _report(),
            _method(),
          ],
        ),
      ),
    );
  }

  Widget _dashboard() {
    final a = _analysis;
    if (_error != null) return Center(child: Text(_error!, style: const TextStyle(color: Colors.red)));
    if (a == null) return const Center(child: CircularProgressIndicator());
    return ListView(
      padding: const EdgeInsets.all(12),
      children: [
        Text(s.t('subtitle'), style: Theme.of(context).textTheme.headlineSmall),
        const SizedBox(height: 8),
        Wrap(
          children: [
            MetricCard(title: 'CRI', value: a.cri.toStringAsFixed(4), note: '0..1'),
            MetricCard(title: 'delta avg', value: a.deltaAvg.toStringAsFixed(4)),
            MetricCard(title: 'MSI max', value: a.msiMax.toStringAsFixed(4)),
            MetricCard(title: 'DI max', value: a.diMax.toStringAsFixed(4)),
            MetricCard(title: s.t('nodes'), value: a.nodes.length.toString()),
            MetricCard(title: s.t('defects'), value: a.defects.length.toString()),
          ],
        ),
        const SizedBox(height: 12),
        SizedBox(height: 260, child: CustomPaint(painter: KltBarChartPainter(a), child: Container())),
        const SizedBox(height: 12),
        Text(s.t('defects'), style: Theme.of(context).textTheme.titleLarge),
        ...a.defects.map((d) => Card(
              child: ListTile(
                leading: CircleAvatar(child: Text((d.severity * 10).round().toString())),
                title: Text('${d.id}: ${d.title}'),
                subtitle: Text(d.message),
              ),
            )),
      ],
    );
  }

  Widget _input() {
    return Padding(
      padding: const EdgeInsets.all(12),
      child: Column(
        children: [
          Row(
            children: [
              ElevatedButton.icon(onPressed: _runAnalysis, icon: const Icon(Icons.play_arrow), label: Text(s.t('analyze'))),
              const SizedBox(width: 8),
              OutlinedButton.icon(
                onPressed: () {
                  _controller.text = _demoProjectJson;
                  _runAnalysis();
                },
                icon: const Icon(Icons.auto_awesome),
                label: Text(s.t('demo')),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Expanded(
            child: TextField(
              controller: _controller,
              expands: true,
              maxLines: null,
              minLines: null,
              decoration: InputDecoration(border: const OutlineInputBorder(), hintText: s.t('jsonHint')),
              style: const TextStyle(fontFamily: 'monospace', fontSize: 13),
            ),
          ),
        ],
      ),
    );
  }

  Widget _visuals() {
    final a = _analysis;
    if (a == null) return const SizedBox.shrink();
    final viz = VisualizationService();
    return ListView(
      padding: const EdgeInsets.all(12),
      children: [
        Text(s.t('scheme'), style: Theme.of(context).textTheme.titleLarge),
        SizedBox(height: 340, child: CustomPaint(painter: KltSchemePainter(a), child: Container())),
        _copyButton(s.t('copySvg'), viz.schemeSvg(a)),
        const Divider(),
        Text(s.t('blueprint'), style: Theme.of(context).textTheme.titleLarge),
        SizedBox(height: 320, child: CustomPaint(painter: KltBlueprintPainter(a), child: Container())),
        _copyButton(s.t('copySvg'), viz.blueprintSvg(a)),
        const Divider(),
        Text(s.t('chart'), style: Theme.of(context).textTheme.titleLarge),
        SizedBox(height: 260, child: CustomPaint(painter: KltBarChartPainter(a), child: Container())),
        _copyButton(s.t('copySvg'), viz.chartSvg(a)),
      ],
    );
  }

  Widget _report() {
    final a = _analysis;
    if (a == null) return const SizedBox.shrink();
    final report = ReportService().markdown(a);
    final json = ReportService().jsonReport(a);
    final handoff = AiHandoffService().buildPrompt(a);
    return ListView(
      padding: const EdgeInsets.all(12),
      children: [
        Row(
          children: [
            _copyButton(s.t('copyReport'), report),
            const SizedBox(width: 8),
            _copyButton(s.t('copyJson'), json),
            const SizedBox(width: 8),
            _copyButton('AI handoff', handoff),
          ],
        ),
        const SizedBox(height: 12),
        SelectableText(report, style: const TextStyle(fontFamily: 'monospace')),
      ],
    );
  }

  Widget _method() {
    return ListView(
      padding: const EdgeInsets.all(18),
      children: [
        Text(s.t('method'), style: Theme.of(context).textTheme.headlineSmall),
        const SizedBox(height: 12),
        Text(s.t('methodText')),
        const SizedBox(height: 16),
        const SelectableText('λ = ((U - R)(I - D)) / ((U - D)(I - R))\nδ = |λ + 1|\nAuth = 1/(1+δ)\nD* = (2UI - UR - IR)/(U+I-2R)\nMSI = |log(Cb/Ca)|\nDI = max(0, (Cmin-Coffer)/Cmin)'),
        const SizedBox(height: 16),
        const Text('KLT 5.1 contains local mode, user-server mode, AI handoff prompt generation, and extension points for DeepSeek/OpenAI API connectors.'),
      ],
    );
  }

  Widget _copyButton(String label, String content) {
    return OutlinedButton.icon(
      onPressed: () => Clipboard.setData(ClipboardData(text: content)),
      icon: const Icon(Icons.copy),
      label: Text(label),
    );
  }
}

const String _demoProjectJson = r'''
{
  "project_id": "KLT51-DEMO",
  "title": "Demo construction and finance project",
  "c_min": 8102300,
  "c_offer": 7454116,
  "resources": [
    {"id": "res_team_a", "name": "Монтажная бригада A", "resource_type": "labor", "capacity": 1},
    {"id": "res_crane", "name": "Кран", "resource_type": "equipment", "capacity": 1}
  ],
  "deliveries": [
    {"id": "del_windows", "name": "Оконные блоки", "delivery_day": 5, "buffer_days": 1, "document_basis": "invoice-001"},
    {"id": "del_alarm", "name": "Охранная сигнализация", "delivery_day": 3, "buffer_days": 0, "document_basis": ""}
  ],
  "works": [
    {"id": "w_demo", "name": "Демонтаж", "start_day": 1, "end_day": 4, "zone": "1 этаж", "resources": ["res_team_a"], "predecessors": [], "deliveries": [], "reper": {"U": 0.9, "I": 0.6, "R": 0.4, "D": 0.7}},
    {"id": "w_windows", "name": "Монтаж окон", "start_day": 3, "end_day": 7, "zone": "1 этаж", "resources": ["res_team_a", "res_crane"], "predecessors": ["w_demo"], "deliveries": ["del_windows"], "reper": {"U": 0.8, "I": 0.55, "R": 0.2, "D": 0.35}},
    {"id": "w_alarm", "name": "Монтаж сигнализации", "start_day": 5, "end_day": 8, "zone": "2 этаж", "resources": ["res_team_a"], "predecessors": [], "deliveries": ["del_alarm"], "reper": {"U": 0.7, "I": 0.6, "R": 0.3, "D": 0.2}}
  ],
  "costs": [
    {"id": "c_total", "name": "Итого", "amount": 8102300, "basis": "contract", "coefficient": 1.0},
    {"id": "c_windows", "name": "Окна", "parent_id": "c_total", "amount": 500000, "basis": "estimate", "coefficient": 1.0, "reper": {"U": 0.7, "I": 0.4, "R": 0.2, "D": 0.3}},
    {"id": "c_alarm", "name": "Сигнализация", "parent_id": "c_total", "amount": 120000, "basis": "", "coefficient": 1.25, "reper": {"U": 0.8, "I": 0.7, "R": 0.5, "D": 0.1}}
  ],
  "finance": [
    {"id": "fin_cash", "description": "Платёж по акту без подтверждённого закрытия", "planned": 1000000, "actual": 1280000, "document_ref": ""}
  ]
}
''';
