/**
 * Deal detail — tasks, docs, compliance, deadlines.
 * Paperless Pipeline replacement: full deal view.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  RefreshControl,
} from 'react-native';
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import type { DealsStackParamList } from '../../navigation/stacks/DealsStack';
import { useTheme } from '../../themes/ThemeProvider';
import TaskItem, { Task } from '../../components/TaskItem';
import { getDeal, getDealTasks, getComplianceItems, getDeadlines, updateTask, Deal } from '../../services/api';

type Props = NativeStackScreenProps<DealsStackParamList, 'DealDetail'>;

interface ComplianceItem {
  id: number;
  name: string;
  status: 'pending' | 'completed' | 'waived';
  due_date: string | null;
  jurisdiction: string;
}

interface Deadline {
  id: number;
  name: string;
  due_date: string;
  status: 'upcoming' | 'due_soon' | 'overdue' | 'completed';
  days_remaining: number;
}

export default function DealDetail({ route, navigation }: Props) {
  const { theme } = useTheme();
  const { id } = route.params;
  const [deal, setDeal] = useState<Deal | null>(null);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [compliance, setCompliance] = useState<ComplianceItem[]>([]);
  const [deadlines, setDeadlines] = useState<Deadline[]>([]);
  const [refreshing, setRefreshing] = useState(false);
  const [activeTab, setActiveTab] = useState<'tasks' | 'compliance' | 'deadlines'>('tasks');

  const load = useCallback(async () => {
    const [dealRes, taskRes, compRes, deadRes] = await Promise.allSettled([
      getDeal(id),
      getDealTasks(id),
      getComplianceItems(id),
      getDeadlines(id),
    ]);

    if (dealRes.status === 'fulfilled' && dealRes.value.data) {
      const d = dealRes.value.data as Deal;
      setDeal(d);
      navigation.setOptions({ title: d.property_address || `Deal #${id}` });
    }
    if (taskRes.status === 'fulfilled' && taskRes.value.data) {
      setTasks(taskRes.value.data as Task[]);
    }
    if (compRes.status === 'fulfilled' && compRes.value.data) {
      setCompliance(compRes.value.data as ComplianceItem[]);
    }
    if (deadRes.status === 'fulfilled' && deadRes.value.data) {
      setDeadlines(deadRes.value.data as Deadline[]);
    }
  }, [id, navigation]);

  useEffect(() => {
    load();
  }, [load]);

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await load();
    setRefreshing(false);
  }, [load]);

  const handleToggleTask = async (task: Task) => {
    const newStatus = task.status === 'completed' ? 'pending' : 'completed';
    setTasks((prev) => prev.map((t) => (t.id === task.id ? { ...t, status: newStatus } : t)));
    await updateTask(task.id, { status: newStatus });
  };

  const formatCurrency = (val: number): string => {
    if (val >= 1_000_000) return `$${(val / 1_000_000).toFixed(2)}M`;
    return `$${val.toLocaleString()}`;
  };

  if (!deal) {
    return (
      <View style={[styles.loading, { backgroundColor: theme.colors.background }]}>
        <Text style={{ color: theme.colors.textSecondary }}>Loading...</Text>
      </View>
    );
  }

  const completedTasks = tasks.filter((t) => t.status === 'completed').length;
  const completedCompliance = compliance.filter((c) => c.status === 'completed').length;

  return (
    <ScrollView
      style={[styles.container, { backgroundColor: theme.colors.background }]}
      refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />}
    >
      {/* Deal Header */}
      <View style={[styles.header, { backgroundColor: theme.colors.card }]}>
        <Text style={[styles.address, { color: theme.colors.text }]}>{deal.property_address}</Text>
        <Text style={[styles.price, { color: theme.colors.primary }]}>{formatCurrency(deal.price)}</Text>

        <View style={styles.metaRow}>
          <View style={[styles.badge, { backgroundColor: theme.colors.accent + '20' }]}>
            <Text style={[styles.badgeText, { color: theme.colors.accent }]}>
              {deal.deal_type.toUpperCase()}
            </Text>
          </View>
          <Text style={[styles.meta, { color: theme.colors.textSecondary }]}>
            Phase {deal.phase} • {deal.jurisdiction}
          </Text>
        </View>

        {/* Progress Bar */}
        <View style={styles.progressRow}>
          <Text style={[styles.progressLabel, { color: theme.colors.textSecondary }]}>
            Tasks: {completedTasks}/{tasks.length}
          </Text>
          <View style={[styles.progressBar, { backgroundColor: theme.colors.border }]}>
            <View
              style={[
                styles.progressFill,
                {
                  width: tasks.length > 0 ? `${(completedTasks / tasks.length) * 100}%` : '0%',
                  backgroundColor: theme.colors.success,
                },
              ]}
            />
          </View>
        </View>

        {/* TC Link */}
        <TouchableOpacity
          style={[styles.tcBtn, { backgroundColor: theme.colors.primary }]}
          onPress={() => navigation.navigate('TransactionTC', { dealId: id })}
        >
          <Text style={styles.tcBtnText}>Open TC Checklist</Text>
        </TouchableOpacity>
      </View>

      {/* Tab Selector */}
      <View style={styles.tabs}>
        {(['tasks', 'compliance', 'deadlines'] as const).map((tab) => (
          <TouchableOpacity
            key={tab}
            style={[styles.tab, activeTab === tab && { borderBottomColor: theme.colors.primary, borderBottomWidth: 2 }]}
            onPress={() => setActiveTab(tab)}
          >
            <Text style={[styles.tabText, { color: activeTab === tab ? theme.colors.primary : theme.colors.textSecondary }]}>
              {tab.charAt(0).toUpperCase() + tab.slice(1)}
            </Text>
          </TouchableOpacity>
        ))}
      </View>

      {/* Tasks */}
      {activeTab === 'tasks' && (
        <View style={[styles.section, { backgroundColor: theme.colors.card }]}>
          {tasks.length === 0 ? (
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>No tasks yet</Text>
          ) : (
            tasks.map((task) => (
              <TaskItem key={task.id} task={task} onToggle={handleToggleTask} onPress={() => {}} />
            ))
          )}
        </View>
      )}

      {/* Compliance */}
      {activeTab === 'compliance' && (
        <View style={[styles.section, { backgroundColor: theme.colors.card }]}>
          <View style={styles.complianceHeader}>
            <Text style={[styles.complianceProgress, { color: theme.colors.textSecondary }]}>
              {completedCompliance}/{compliance.length} items complete
            </Text>
          </View>
          {compliance.length === 0 ? (
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>No compliance items</Text>
          ) : (
            compliance.map((item) => (
              <View key={item.id} style={[styles.complianceRow, { borderBottomColor: theme.colors.border }]}>
                <View style={[styles.complianceDot, {
                  backgroundColor: item.status === 'completed' ? theme.colors.success :
                                   item.status === 'waived' ? theme.colors.textSecondary : theme.colors.warning,
                }]} />
                <View style={styles.complianceInfo}>
                  <Text style={[styles.complianceName, { color: theme.colors.text }]}>{item.name}</Text>
                  {item.due_date && (
                    <Text style={[styles.complianceDue, { color: theme.colors.textSecondary }]}>
                      Due: {new Date(item.due_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                    </Text>
                  )}
                </View>
                <Text style={[styles.complianceStatus, {
                  color: item.status === 'completed' ? theme.colors.success : theme.colors.warning,
                }]}>
                  {item.status.toUpperCase()}
                </Text>
              </View>
            ))
          )}
        </View>
      )}

      {/* Deadlines */}
      {activeTab === 'deadlines' && (
        <View style={[styles.section, { backgroundColor: theme.colors.card }]}>
          {deadlines.length === 0 ? (
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>No deadlines</Text>
          ) : (
            deadlines.map((dl) => (
              <View key={dl.id} style={[styles.deadlineRow, { borderBottomColor: theme.colors.border }]}>
                <View style={[styles.daysCircle, {
                  backgroundColor: dl.status === 'overdue' ? theme.colors.error :
                                   dl.status === 'due_soon' ? theme.colors.warning :
                                   dl.status === 'completed' ? theme.colors.success : theme.colors.info,
                }]}>
                  <Text style={styles.daysText}>
                    {dl.status === 'completed' ? '✓' : dl.days_remaining}
                  </Text>
                  {dl.status !== 'completed' && (
                    <Text style={styles.daysLabel}>days</Text>
                  )}
                </View>
                <View style={styles.deadlineInfo}>
                  <Text style={[styles.deadlineName, { color: theme.colors.text }]}>{dl.name}</Text>
                  <Text style={[styles.deadlineDate, { color: theme.colors.textSecondary }]}>
                    {new Date(dl.due_date).toLocaleDateString('en-US', {
                      weekday: 'short',
                      month: 'short',
                      day: 'numeric',
                    })}
                  </Text>
                </View>
              </View>
            ))
          )}
        </View>
      )}

      <View style={styles.bottomPad} />
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  loading: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  container: { flex: 1 },
  header: { padding: 20 },
  address: { fontSize: 20, fontWeight: '700', marginBottom: 4 },
  price: { fontSize: 26, fontWeight: '800', marginBottom: 10 },
  metaRow: { flexDirection: 'row', alignItems: 'center', gap: 10, marginBottom: 14 },
  badge: { paddingHorizontal: 10, paddingVertical: 3, borderRadius: 6 },
  badgeText: { fontSize: 11, fontWeight: '700' },
  meta: { fontSize: 13 },
  progressRow: { marginBottom: 14 },
  progressLabel: { fontSize: 12, marginBottom: 4 },
  progressBar: { height: 6, borderRadius: 3, overflow: 'hidden' },
  progressFill: { height: '100%', borderRadius: 3 },
  tcBtn: { height: 44, borderRadius: 10, justifyContent: 'center', alignItems: 'center' },
  tcBtnText: { color: '#FFF', fontWeight: '700', fontSize: 15 },
  tabs: { flexDirection: 'row', borderBottomWidth: 1, borderBottomColor: '#E5E7EB' },
  tab: { flex: 1, paddingVertical: 12, alignItems: 'center' },
  tabText: { fontSize: 14, fontWeight: '600' },
  section: { minHeight: 100 },
  emptyText: { padding: 20, fontSize: 14, textAlign: 'center' },
  complianceHeader: { padding: 12 },
  complianceProgress: { fontSize: 13 },
  complianceRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  complianceDot: { width: 10, height: 10, borderRadius: 5, marginRight: 12 },
  complianceInfo: { flex: 1 },
  complianceName: { fontSize: 14, fontWeight: '500' },
  complianceDue: { fontSize: 12, marginTop: 2 },
  complianceStatus: { fontSize: 10, fontWeight: '700' },
  deadlineRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  daysCircle: {
    width: 44,
    height: 44,
    borderRadius: 22,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  daysText: { color: '#FFF', fontSize: 16, fontWeight: '800' },
  daysLabel: { color: '#FFF', fontSize: 8, marginTop: -2 },
  deadlineInfo: { flex: 1 },
  deadlineName: { fontSize: 14, fontWeight: '500' },
  deadlineDate: { fontSize: 12, marginTop: 2 },
  bottomPad: { height: 40 },
});
