'use client';

import { useState, useRef, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { LayoutShell } from '../../../../components/layout-shell';
import { MobileLayout } from '@/components/mobile-layout';
import { useAnonymousReport, ReportLocation } from '../../../../hooks/use-anonymous-report';
import { Camera, Send, X, AlertTriangle, CheckCircle2, Mic, Video, StopCircle, Upload, Play, Pause, MapPin, Loader2 } from 'lucide-react';
import clsx from 'clsx';

// Ghana regions for mapping coordinates
const GHANA_REGIONS = [
  { name: 'Greater Accra', bounds: { minLat: 5.5, maxLat: 5.95, minLng: -0.5, maxLng: 0.15 } },
  { name: 'Ashanti', bounds: { minLat: 6.0, maxLat: 7.5, minLng: -2.3, maxLng: -0.8 } },
  { name: 'Western', bounds: { minLat: 4.7, maxLat: 6.3, minLng: -3.2, maxLng: -1.9 } },
  { name: 'Central', bounds: { minLat: 5.0, maxLat: 6.0, minLng: -1.9, maxLng: -0.5 } },
  { name: 'Eastern', bounds: { minLat: 5.8, maxLat: 7.0, minLng: -1.2, maxLng: 0.5 } },
  { name: 'Volta', bounds: { minLat: 5.8, maxLat: 8.2, minLng: 0.0, maxLng: 1.2 } },
  { name: 'Northern', bounds: { minLat: 8.5, maxLat: 10.7, minLng: -2.5, maxLng: 0.5 } },
  { name: 'Upper East', bounds: { minLat: 10.3, maxLat: 11.2, minLng: -1.0, maxLng: 0.2 } },
  { name: 'Upper West', bounds: { minLat: 9.8, maxLat: 11.0, minLng: -2.8, maxLng: -1.4 } },
  { name: 'Bono', bounds: { minLat: 7.0, maxLat: 8.5, minLng: -2.8, maxLng: -1.5 } },
  { name: 'Bono East', bounds: { minLat: 7.2, maxLat: 8.5, minLng: -1.8, maxLng: -0.3 } },
  { name: 'Ahafo', bounds: { minLat: 6.5, maxLat: 7.5, minLng: -2.6, maxLng: -1.8 } },
  { name: 'Savannah', bounds: { minLat: 8.0, maxLat: 9.5, minLng: -2.0, maxLng: 0.0 } },
  { name: 'North East', bounds: { minLat: 10.0, maxLat: 10.9, minLng: -0.5, maxLng: 0.6 } },
  { name: 'Oti', bounds: { minLat: 7.5, maxLat: 8.5, minLng: 0.0, maxLng: 0.8 } },
  { name: 'Western North', bounds: { minLat: 5.5, maxLat: 6.8, minLng: -3.0, maxLng: -2.0 } },
];

function getRegionFromCoords(lat: number, lng: number): string {
  for (const region of GHANA_REGIONS) {
    if (
      lat >= region.bounds.minLat && lat <= region.bounds.maxLat &&
      lng >= region.bounds.minLng && lng <= region.bounds.maxLng
    ) {
      return region.name;
    }
  }
  return 'Unknown';
}

export default function ReportIssuePage() {
  const router = useRouter();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const cameraInputRef = useRef<HTMLInputElement>(null);
  const videoInputRef = useRef<HTMLInputElement>(null);
  const [description, setDescription] = useState('');
  const [media, setMedia] = useState<File | null>(null);
  const [mediaPreview, setMediaPreview] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  
  // Location State
  const [location, setLocation] = useState<ReportLocation | null>(null);
  const [locationLoading, setLocationLoading] = useState(false);
  const [locationError, setLocationError] = useState<string | null>(null);
  
  // Audio Recording State
  const [isRecording, setIsRecording] = useState(false);
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
  const audioChunksRef = useRef<Blob[]>([]);
  const [recordingTime, setRecordingTime] = useState(0);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  const reportMutation = useAnonymousReport();

  // Auto-capture location on mount
  useEffect(() => {
    captureLocation();
  }, []);

  const captureLocation = async () => {
    if (!navigator.geolocation) {
      setLocationError('Geolocation is not supported by your browser');
      return;
    }

    setLocationLoading(true);
    setLocationError(null);

    navigator.geolocation.getCurrentPosition(
      async (position) => {
        const { latitude, longitude, accuracy } = position.coords;
        const region = getRegionFromCoords(latitude, longitude);
        
        // Try to get address using reverse geocoding (optional)
        let address = '';
        try {
          // Simple reverse geocoding using Nominatim (free, no API key)
          const response = await fetch(
            `https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}&zoom=16`
          );
          if (response.ok) {
            const data = await response.json();
            address = data.display_name || '';
          }
        } catch (e) {
          // Silent fail - address is optional
          console.log('Reverse geocoding failed', e);
        }

        setLocation({
          latitude,
          longitude,
          accuracy,
          region,
          address,
        });
        setLocationLoading(false);
      },
      (error) => {
        setLocationError(
          error.code === 1 
            ? 'Location access denied. Please enable location permissions.' 
            : 'Could not get your location. Please try again.'
        );
        setLocationLoading(false);
      },
      {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 60000,
      }
    );
  };

  const handleMediaSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0];
      if (file) {
          setMedia(file);
          const url = URL.createObjectURL(file);
          setMediaPreview(url);
      }
  };

  const startRecording = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      const mediaRecorder = new MediaRecorder(stream);
      mediaRecorderRef.current = mediaRecorder;
      audioChunksRef.current = [];

      mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
          audioChunksRef.current.push(event.data);
        }
      };

      mediaRecorder.onstop = () => {
        const audioBlob = new Blob(audioChunksRef.current, { type: 'audio/mp3' });
        const audioFile = new File([audioBlob], `voice_report_${Date.now()}.mp3`, { type: 'audio/mp3' });
        setMedia(audioFile);
        const url = URL.createObjectURL(audioBlob);
        setMediaPreview(url);
        
        // Stop all tracks
        stream.getTracks().forEach(track => track.stop());
      };

      mediaRecorder.start();
      setIsRecording(true);
      
      // Start timer
      setRecordingTime(0);
      timerRef.current = setInterval(() => {
        setRecordingTime(prev => prev + 1);
      }, 1000);

    } catch (err) {
      console.error('Error accessing microphone:', err);
      alert('Could not access microphone. Please check permissions.');
    }
  };

  const stopRecording = () => {
    if (mediaRecorderRef.current && isRecording) {
      mediaRecorderRef.current.stop();
      setIsRecording(false);
      if (timerRef.current) clearInterval(timerRef.current);
    }
  };

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const clearMedia = () => {
    setMedia(null);
    setMediaPreview(null);
    if (fileInputRef.current) fileInputRef.current.value = '';
    if (cameraInputRef.current) cameraInputRef.current.value = '';
    if (videoInputRef.current) videoInputRef.current.value = '';
    // Also clean up any recording streams if exist (though handled in stop)
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!description && !media) return;

    reportMutation.mutate({ description, media, location: location || undefined }, {
      onSuccess: () => {
        setSuccess(true);
        setDescription('');
        clearMedia();
        setTimeout(() => {
          router.push('/field-staff');
        }, 3000);
      }
    });
  };

  if (success) {
    return (
      <MobileLayout className="bg-slate-900 flex items-center justify-center p-6 text-center">
        <div className="space-y-6">
            <div className="flex justify-center">
                <div className="rounded-full bg-emerald-500/20 p-4 ring-1 ring-emerald-500/50">
                    <CheckCircle2 className="h-12 w-12 text-emerald-500" />
                </div>
            </div>
          <h2 className="text-2xl font-bold text-white">Report Sent</h2>
          <p className="text-slate-400">Thank you for your anonymous report. Your identity has not been stored.</p>
          <button 
            onClick={() => router.push('/field-staff')}
            className="w-full rounded-xl bg-slate-800 py-3 font-semibold text-white mt-8"
          >
            Return Home
          </button>
        </div>
      </MobileLayout>
    );
  }

  return (
    <MobileLayout className="bg-slate-950 text-white min-h-screen">
      <div className="flex items-center justify-between p-4 border-b border-slate-800 bg-slate-950/50 backdrop-blur-xl sticky top-0 z-10">
        <button onClick={() => router.back()} className="p-2 -ml-2 text-slate-400 hover:text-white">
          <X className="h-6 w-6" />
        </button>
        <span className="font-bold text-lg tracking-tight">See Something, Say Something</span>
        <div className="w-8" /> 
      </div>

      <form onSubmit={handleSubmit} className="p-4 space-y-6 max-w-lg mx-auto pb-20">
        <div className="rounded-2xl bg-gradient-to-br from-indigo-500/10 to-purple-500/10 p-4 border border-indigo-500/20">
            <div className="flex gap-3 text-indigo-300 mb-2">
                <AlertTriangle className="h-5 w-5 shrink-0" />
                <p className="text-xs font-medium leading-relaxed">
                    This report is 100% anonymous. We do not collect any personal information. The information submitted is used to uphold the integrity of the programme.
                </p>
            </div>
        </div>

        {/* Location Indicator */}
        <div className="rounded-2xl bg-slate-900 border border-slate-700 p-4">
          <div className="flex items-center justify-between mb-2">
            <div className="flex items-center gap-2 text-slate-400">
              <MapPin className="h-4 w-4" />
              <span className="text-xs font-medium uppercase tracking-wider">Your Location</span>
            </div>
            {!location && !locationLoading && (
              <button
                type="button"
                onClick={captureLocation}
                className="text-xs text-indigo-400 hover:text-indigo-300"
              >
                Retry
              </button>
            )}
          </div>
          
          {locationLoading && (
            <div className="flex items-center gap-2 text-slate-500">
              <Loader2 className="h-4 w-4 animate-spin" />
              <span className="text-sm">Detecting location...</span>
            </div>
          )}
          
          {locationError && (
            <div className="text-amber-400 text-sm">{locationError}</div>
          )}
          
          {location && (
            <div className="space-y-1">
              <div className="flex items-center gap-2">
                <span className="inline-flex items-center rounded-full bg-emerald-500/20 px-2.5 py-1 text-xs font-medium text-emerald-400 ring-1 ring-inset ring-emerald-500/30">
                  {location.region} Region
                </span>
                {location.accuracy && (
                  <span className="text-xs text-slate-500">
                    ±{Math.round(location.accuracy)}m accuracy
                  </span>
                )}
              </div>
              {location.address && (
                <p className="text-xs text-slate-500 truncate" title={location.address}>
                  {location.address.split(',').slice(0, 3).join(', ')}
                </p>
              )}
            </div>
          )}
        </div>

        <div className="space-y-4">
            <div className="relative">
                <textarea
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="Describe what you observed..."
                    className="w-full h-40 bg-slate-900 border-0 rounded-2xl p-4 text-white placeholder-slate-500 focus:ring-2 focus:ring-indigo-500 resize-none text-lg"
                />
            </div>

            {mediaPreview ? (
                <div className="relative rounded-2xl overflow-hidden border border-slate-800 bg-slate-900">
                    <div className="aspect-video w-full bg-black flex items-center justify-center">
                        {media?.type.startsWith('image') && (
                           <img src={mediaPreview} alt="Preview" className="max-h-64 h-full w-full object-contain" />
                        )}
                        {media?.type.startsWith('video') && (
                           <video src={mediaPreview} controls className="max-h-64 h-full w-full object-contain" />
                        )}
                        {media?.type.startsWith('audio') && (
                            <div className="w-full h-full flex flex-col items-center justify-center bg-slate-900 text-indigo-400">
                                <Mic className="h-12 w-12 mb-4" />
                                <audio src={mediaPreview} controls className="w-3/4" />
                            </div>
                        )}
                    </div>
                    <button
                        type="button"
                        onClick={clearMedia}
                        className="absolute top-2 right-2 p-1.5 bg-black/50 text-white rounded-full backdrop-blur-md hover:bg-red-500 transition"
                    >
                        <X className="h-4 w-4" />
                    </button>
                    <div className="absolute bottom-2 left-2 px-2 py-1 bg-black/60 rounded text-xs text-white">
                        {media?.name}
                    </div>
                </div>
            ) : (
                <div className="grid grid-cols-2 gap-3">
                    <button
                        type="button"
                        onClick={() => cameraInputRef.current?.click()}
                        className="flex flex-col items-center justify-center gap-2 h-24 rounded-2xl border border-dashed border-slate-700 bg-slate-900/50 hover:bg-slate-800 transition active:scale-95"
                    >
                        <Camera className="h-6 w-6 text-indigo-400" />
                        <span className="text-xs font-medium text-slate-400">Take Photo</span>
                    </button>

                    <button
                        type="button"
                        onClick={() => videoInputRef.current?.click()}
                        className="flex flex-col items-center justify-center gap-2 h-24 rounded-2xl border border-dashed border-slate-700 bg-slate-900/50 hover:bg-slate-800 transition active:scale-95"
                    >
                        <Video className="h-6 w-6 text-pink-400" />
                        <span className="text-xs font-medium text-slate-400">Record Video</span>
                    </button>

                    <button
                        type="button"
                        onClick={() => fileInputRef.current?.click()}
                        className="flex flex-col items-center justify-center gap-2 h-24 rounded-2xl border border-dashed border-slate-700 bg-slate-900/50 hover:bg-slate-800 transition active:scale-95"
                    >
                        <Upload className="h-6 w-6 text-blue-400" />
                        <span className="text-xs font-medium text-slate-400">Upload File</span>
                    </button>
                    
                    {isRecording ? (
                        <button
                            type="button"
                            onClick={stopRecording}
                            className="flex flex-col items-center justify-center gap-2 h-24 rounded-2xl border border-red-500/50 bg-red-500/10 hover:bg-red-500/20 transition animate-pulse"
                        >
                            <StopCircle className="h-8 w-8 text-red-500" />
                            <span className="text-sm font-bold text-red-400">{formatTime(recordingTime)}</span>
                            <span className="text-xs text-red-400">Tap to Stop</span>
                        </button>
                    ) : (
                        <button
                            type="button"
                            onClick={startRecording}
                            className="flex flex-col items-center justify-center gap-2 h-24 rounded-2xl border border-dashed border-slate-700 bg-slate-900/50 hover:bg-slate-800 transition active:scale-95 group"
                        >
                            <Mic className="h-6 w-6 text-slate-400 group-hover:text-amber-400 transition-colors" />
                            <span className="text-xs font-medium text-slate-400 group-hover:text-slate-300">Record Audio</span>
                        </button>
                    )}
                </div>
            )}
            
            <input 
                type="file" 
                ref={fileInputRef}
                accept="image/*,video/*"
                className="hidden"
                onChange={handleMediaSelect}
            />
            <input 
                type="file" 
                ref={cameraInputRef}
                accept="image/*"
                capture="environment"
                className="hidden"
                onChange={handleMediaSelect}
            />
            <input 
                type="file" 
                ref={videoInputRef}
                accept="video/*"
                capture="environment"
                className="hidden"
                onChange={handleMediaSelect}
            />
        </div>

        <button
            type="submit"
            disabled={(!description && !media) || reportMutation.isPending}
            className={clsx(
                "w-full py-4 rounded-xl font-bold text-center text-white text-lg shadow-lg shadow-indigo-500/25 transition-all active:scale-[0.98] flex items-center justify-center gap-2",
                (!description && !media) 
                    ? "bg-slate-800 text-slate-500 cursor-not-allowed" 
                    : "bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500"
            )}
        >
            {reportMutation.isPending ? (
                <div className="h-6 w-6 border-2 border-white/30 border-t-white rounded-full animate-spin" />
            ) : (
                <>
                    <Send className="h-5 w-5" />
                    <span>Submit Report</span>
                </>
            )}
        </button>
      </form>
    </MobileLayout>
  );
}
