import axios from 'axios';
import { useEffect, useState } from 'react';
import { StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { DriverShell } from '../components/driver-shell';
import { API_URL } from '../src/runtime-config';
import { useDriverSession } from '../src/store/session';
import { driverTheme } from '../src/lib/driver-ui';
import { extractErrorMessage } from '../src/lib/driver-api';

type DriverProfile = {
  id: string;
  fullName: string;
  vehiclePlate?: string | null;
  vehicleModel?: string | null;
  pixKey?: string | null;
  user: {
    email?: string | null;
    phone?: string | null;
  };
};

export default function DriverAccountScreen() {
  const { accessToken } = useDriverSession();
  const [form, setForm] = useState({
    fullName: '',
    phone: '',
    vehiclePlate: '',
    vehicleModel: '',
    pixKey: '',
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const load = async () => {
    if (!accessToken) {
      setError('Sessao do entregador nao encontrada.');
      setLoading(false);
      return;
    }

    setLoading(true);
    try {
      const response = await axios.get<DriverProfile>(`${API_URL}/driver/profile`, {
        headers: { Authorization: `Bearer ${accessToken}` },
      });
      setForm({
        fullName: response.data.fullName ?? '',
        phone: response.data.user.phone ?? '',
        vehiclePlate: response.data.vehiclePlate ?? '',
        vehicleModel: response.data.vehicleModel ?? '',
        pixKey: response.data.pixKey ?? '',
      });
      setError('');
    } catch (loadError) {
      setError(extractErrorMessage(loadError, 'Falha ao carregar o perfil do entregador.'));
    } finally {
      setLoading(false);
    }
  };

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

  const save = async () => {
    if (!accessToken) {
      return;
    }

    setSaving(true);
    setError('');
    setSuccess('');
    try {
      await axios.patch(`${API_URL}/driver/profile`, form, {
        headers: { Authorization: `Bearer ${accessToken}` },
      });
      setSuccess('Dados atualizados com sucesso.');
    } catch (saveError) {
      setError(extractErrorMessage(saveError, 'Falha ao salvar os dados do entregador.'));
    } finally {
      setSaving(false);
    }
  };

  return (
    <DriverShell
      eyebrow="Conta"
      title="Perfil pronto para operar"
      subtitle="Mantenha veiculo, telefone e chave PIX certos para evitar bloqueio de repasse e ruído na operacao."
    >
      <View style={styles.card}>
        <Text style={styles.label}>Nome completo</Text>
        <TextInput value={form.fullName} onChangeText={(value) => setForm((current) => ({ ...current, fullName: value }))} placeholder="Nome completo" placeholderTextColor="#94A3B8" style={styles.input} />
        <Text style={styles.label}>Telefone</Text>
        <TextInput value={form.phone} onChangeText={(value) => setForm((current) => ({ ...current, phone: value }))} placeholder="Telefone com DDD" placeholderTextColor="#94A3B8" style={styles.input} />
        <Text style={styles.label}>Placa da moto</Text>
        <TextInput value={form.vehiclePlate} onChangeText={(value) => setForm((current) => ({ ...current, vehiclePlate: value.toUpperCase() }))} placeholder="ABC1D23" placeholderTextColor="#94A3B8" style={styles.input} />
        <Text style={styles.label}>Modelo da moto</Text>
        <TextInput value={form.vehicleModel} onChangeText={(value) => setForm((current) => ({ ...current, vehicleModel: value }))} placeholder="Ex.: Honda CG 160" placeholderTextColor="#94A3B8" style={styles.input} />
        <Text style={styles.label}>Chave PIX</Text>
        <TextInput value={form.pixKey} onChangeText={(value) => setForm((current) => ({ ...current, pixKey: value }))} placeholder="CPF, telefone, e-mail ou chave aleatoria" placeholderTextColor="#94A3B8" style={styles.input} />
        <Text style={styles.helper}>Use a mesma chave cadastrada no banco para reduzir atraso no repasse das corridas.</Text>

        {error ? <Text style={styles.error}>{error}</Text> : null}
        {success ? <Text style={styles.success}>{success}</Text> : null}
        {loading ? <Text style={styles.helper}>Carregando dados atuais...</Text> : null}

        <TouchableOpacity onPress={() => void save()} style={styles.button} disabled={saving || loading}>
          <Text style={styles.buttonText}>{saving ? 'Salvando...' : 'Salvar dados'}</Text>
        </TouchableOpacity>
      </View>
    </DriverShell>
  );
}

const styles = StyleSheet.create({
  card: {
    borderRadius: 24,
    padding: 18,
    backgroundColor: driverTheme.card,
  },
  label: { marginTop: 12, fontSize: 12, color: '#475569', fontWeight: '800', textTransform: 'uppercase' },
  input: { marginTop: 10, borderRadius: 16, borderWidth: 1, borderColor: '#CBD5E1', backgroundColor: '#FFFFFF', paddingHorizontal: 14, paddingVertical: 12, color: '#0F172A' },
  helper: { marginTop: 12, color: '#64748B', fontSize: 13, lineHeight: 19 },
  error: { marginTop: 12, color: '#B91C1C', fontSize: 13, fontWeight: '700' },
  success: { marginTop: 12, color: '#047857', fontSize: 13, fontWeight: '700' },
  button: { marginTop: 16, borderRadius: 999, backgroundColor: driverTheme.accent, paddingVertical: 14, alignItems: 'center' },
  buttonText: { color: '#FFFFFF', fontWeight: '900' },
});
