import { View, Text, Modal, ScrollView, TouchableOpacity, KeyboardAvoidingView, Platform } from 'react-native';
import { useState } from 'react';
import { X } from 'lucide-react-native';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { DatePicker } from '@/components/ui/DatePicker';
import { TopicSelector } from '@/components/visits/TopicSelector';
import { useUserStore } from '@/store/useUserStore';
import { getDatabase } from '@/lib/database';
import { newVisitId } from '@/lib/visitHelpers';

interface Props {
  contactId: string;
  contactName: string;
  visible: boolean;
  onClose: () => void;
  onSaved: () => void;
}

const RESPONSE_OPTIONS = ['Interested', 'Not Interested', 'Busy', 'No Answer', 'Do Not Call'];

export function LogVisitSheet({ contactId, contactName, visible, onClose, onSaved }: Props) {
  const user = useUserStore((s) => s.user);
  const [visitDate, setVisitDate] = useState<number>(Math.floor(Date.now() / 1000));
  const [topic, setTopic] = useState('');
  const [response, setResponse] = useState('');
  const [remarks, setRemarks] = useState('');
  const [nextVisitDate, setNextVisitDate] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);

  function reset() {
    setVisitDate(Math.floor(Date.now() / 1000));
    setTopic(''); setResponse(''); setRemarks(''); setNextVisitDate(null);
  }

  async function handleSave() {
    setLoading(true);
    try {
      const db = await getDatabase();
      const now = Math.floor(Date.now() / 1000);
      const id = newVisitId();
      await db.runAsync(
        `INSERT INTO visits (id, contact_id, visited_by_name, visited_by_id, visit_date, topic, response, remarks, next_visit_date, created_at, updated_at)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [id, contactId, user?.displayName ?? 'Unknown', user?.id ?? 'unknown',
         visitDate, topic || null, response || null, remarks.trim() || null,
         nextVisitDate, now, now]
      );
      // Update contact status if response is Do Not Call
      if (response === 'Do Not Call') {
        await db.runAsync('UPDATE contacts SET status=?, updated_at=? WHERE id=?', ['Do Not Call', now, contactId]);
      } else if (response === 'Interested') {
        await db.runAsync('UPDATE contacts SET status=?, updated_at=? WHERE id=?', ['Return Visit', now, contactId]);
      }
      reset();
      onSaved();
    } finally {
      setLoading(false);
    }
  }

  return (
    <Modal visible={visible} animationType="slide" presentationStyle="pageSheet" onRequestClose={() => { reset(); onClose(); }}>
      <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} className="flex-1">
        <View className="flex-1 bg-secondary">
          <View className="flex-row items-center justify-between px-4 py-4 border-b border-gray-200 bg-white">
            <TouchableOpacity onPress={() => { reset(); onClose(); }}><X size={22} color="#2C3E50" /></TouchableOpacity>
            <Text className="text-charcoal font-semibold text-lg">Log Visit</Text>
            <View style={{ width: 22 }} />
          </View>

          <ScrollView className="flex-1 px-4 pt-4" keyboardShouldPersistTaps="handled">
            <Text className="text-gray-500 text-sm mb-4">Contact: <Text className="text-charcoal font-medium">{contactName}</Text></Text>

            <DatePicker label="Visit Date" value={visitDate} onChange={setVisitDate} />
            <TopicSelector value={topic} onChange={setTopic} />

            <Text className="text-charcoal font-medium mb-2">Response</Text>
            <View className="flex-row flex-wrap gap-2 mb-4">
              {RESPONSE_OPTIONS.map((r) => (
                <TouchableOpacity key={r} onPress={() => setResponse(r === response ? '' : r)} className={`px-3 py-1.5 rounded-full border ${response === r ? 'bg-primary border-primary' : 'bg-white border-gray-200'}`}>
                  <Text className={`text-sm ${response === r ? 'text-white' : 'text-charcoal'}`}>{r}</Text>
                </TouchableOpacity>
              ))}
            </View>

            <Input label="Remarks" placeholder="Any notes about this visit..." value={remarks} onChangeText={setRemarks} multiline numberOfLines={3} />
            <DatePicker label="Schedule Next Visit (optional)" value={nextVisitDate} onChange={setNextVisitDate} />
            <View className="h-8" />
          </ScrollView>

          <View className="px-4 py-4 border-t border-gray-200 bg-white">
            <Button label="Save Visit" onPress={handleSave} loading={loading} />
          </View>
        </View>
      </KeyboardAvoidingView>
    </Modal>
  );
}
