import React, { useState } from 'react';
import { Alert, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import type { RouteProp } from '@react-navigation/native';
import { useNavigation, useRoute } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import type { RootStackParamList } from '@/navigation/RootNavigator';
import { saveKiosk, toSavedKiosk } from '@/features/favorites/favoritesStore';
import { useTheme } from '@/theme/ThemeContext';
import type { SpacePolicy } from 'parksmarter-client';

type DetailRoute = RouteProp<RootStackParamList, 'MeterDetail'>;

/** MaxTime of 0 means no cap. */
function fmtMaxTime(m?: number): string {
  if (m == null) return '—';
  if (m <= 0) return 'Unlimited';
  return `${m} min`;
}

/** Zone rate is a string that may include '$'/spaces, or be "NA" / a placeholder. */
function fmtRate(r?: string): string | undefined {
  if (r == null) return undefined;
  const n = Number(String(r).replace(/^\$\s*/, '').trim());
  return Number.isFinite(n) ? `$${n.toFixed(2)}` : undefined;
}

/**
 * A human rate label from the CURRENTLY-active policy. Only "Hour" is a real
 * hourly price; "Variable" carries a placeholder number (see-signs), so never
 * render it as $/hr.
 */
function currentRateLabel(policy: SpacePolicy | undefined, zoneRate?: string): string {
  const t = (policy?.RateType ?? '').toLowerCase();
  if (t === 'hour' && typeof policy?.Rate === 'number' && policy.Rate > 0) {
    return `$${policy.Rate}/hr`;
  }
  if (t.includes('variable')) return 'Variable — see signs';
  if (t.includes('free')) return 'Free now';
  if (t.includes('no parking')) return 'No parking now';
  if (t.includes('prepay')) return 'Prepay';
  return fmtRate(zoneRate) ?? '—';
}

/**
 * Policies are time-of-day windows. A NEGATIVE `Rate` is a sentinel, not a price:
 * the meaning is in `RateType` (e.g. "No Parking", "Free"); only a positive Rate
 * is a real $/hr charge.
 */
function policyMeta(p: SpacePolicy): { title: string; rate?: string; color?: string } {
  const rt = (p.RateType ?? '').toLowerCase();
  const color = rt.includes('no parking')
    ? '#c0392b'
    : rt.includes('free')
      ? '#2e7d32'
      : undefined;
  const title = p.DisplayString || p.MessageHeader || p.RateType || 'Rate policy';
  // Only a true "Hour" policy is an hourly price; "Variable" etc. carry a
  // placeholder number, so don't render those as $/hr.
  const rate =
    rt === 'hour' && typeof p.Rate === 'number' && p.Rate > 0 ? `$${p.Rate}/hr` : undefined;
  return { title, rate, color };
}

type Nav = NativeStackNavigationProp<RootStackParamList>;

export function MeterDetailScreen() {
  const { colors } = useTheme();
  const navigation = useNavigation<Nav>();
  const { params } = useRoute<DetailRoute>();
  const z = params.zone;
  const [saved, setSaved] = useState(false);

  const onSave = async () => {
    await saveKiosk(toSavedKiosk(z));
    setSaved(true);
    Alert.alert('Saved', `${z.ZoneName ?? 'Kiosk'} added to your saved kiosks.`);
  };

  const firstSpace = z.Spaces?.[0];
  const currentPolicy = firstSpace?.Policies?.find((p) => p.CurrentSlot);

  const Field = ({ label, value }: { label: string; value?: string }) => (
    <View style={[styles.field, { backgroundColor: colors.card }]}>
      <Text style={[styles.fieldLabel, { color: colors.subtext }]}>{label}</Text>
      <Text style={[styles.fieldValue, { color: colors.text }]}>{value ?? '—'}</Text>
    </View>
  );

  return (
    <ScrollView
      style={{ backgroundColor: colors.bg }}
      contentContainerStyle={{ padding: 16 }}
    >
      <Text style={[styles.title, { color: colors.text }]}>
        {z.ZoneName ?? 'Parking meter'}
      </Text>
      {z.ZoneLocation ? (
        <Text style={[styles.sub, { color: colors.subtext }]}>{z.ZoneLocation}</Text>
      ) : null}

      <View style={styles.row}>
        <Field label="Scanner code" value={z.ScannerCode} />
        <Field label="Serial" value={z.TerminalSerNo} />
      </View>
      <View style={styles.row}>
        <Field label="Rate" value={currentRateLabel(currentPolicy, z.Rate)} />
        <Field label="Max time" value={fmtMaxTime(z.MaxTime)} />
      </View>
      <View style={styles.row}>
        <Field
          label="Occupancy"
          value={z.PercentageFull != null ? `${z.PercentageFull}% full` : undefined}
        />
        <Field label="Spaces" value={z.Spaces ? String(z.Spaces.length) : undefined} />
      </View>

      {firstSpace?.Policies?.length ? (
        <View style={[styles.card, { backgroundColor: colors.card }]}>
          <Text style={[styles.cardTitle, { color: colors.text }]}>Rate policies</Text>
          {firstSpace.Policies.slice(0, 10).map((p, i) => {
            const { title, rate, color } = policyMeta(p);
            return (
              <View key={i} style={styles.policyRow}>
                <View
                  style={[styles.policyDot, { backgroundColor: color ?? colors.primary }]}
                />
                <Text style={[styles.policyTitle, { color: colors.text }]} numberOfLines={2}>
                  {title}
                </Text>
                {rate ? (
                  <Text style={[styles.policyRate, { color: colors.subtext }]}>{rate}</Text>
                ) : null}
              </View>
            );
          })}
        </View>
      ) : null}

      <TouchableOpacity
        style={[styles.button, { backgroundColor: saved ? '#2e7d32' : colors.card }]}
        onPress={onSave}
        disabled={saved}
      >
        <Text style={[styles.buttonText, { color: saved ? '#fff' : colors.text }]}>
          {saved ? 'Saved ✓' : 'Save kiosk'}
        </Text>
      </TouchableOpacity>

      <TouchableOpacity
        style={[styles.button, { backgroundColor: colors.primary }]}
        onPress={() => navigation.navigate('StartSession', { zone: z })}
      >
        <Text style={[styles.buttonText, { color: '#fff' }]}>Start parking session</Text>
      </TouchableOpacity>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  title: { fontSize: 24, fontWeight: '700' },
  sub: { marginBottom: 12 },
  row: { flexDirection: 'row', gap: 12, marginTop: 8 },
  field: { flex: 1, borderRadius: 10, padding: 12 },
  fieldLabel: { fontSize: 12 },
  fieldValue: { fontSize: 16, fontWeight: '600', marginTop: 2 },
  card: { borderRadius: 10, padding: 14, marginTop: 16 },
  cardTitle: { fontWeight: '700', marginBottom: 8, fontSize: 15 },
  policyRow: { flexDirection: 'row', alignItems: 'center', gap: 8, marginBottom: 10 },
  policyDot: { width: 9, height: 9, borderRadius: 5 },
  policyTitle: { fontSize: 14, fontWeight: '600', flex: 1 },
  policyRate: { fontSize: 13, fontWeight: '600' },
  button: { marginTop: 16, borderRadius: 10, padding: 16, alignItems: 'center' },
  buttonText: { fontWeight: '600', fontSize: 16 },
});
