'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from '@/lib/i18n';
import { MapPin, Navigation, Loader2, Ruler, Info } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { authFetch } from '@/lib/api';

interface AreaLocation {
  id: string;
  name: string;
  code: string;
  latitude: number | null;
  longitude: number | null;
}

interface TaskLocation {
  id: string;
  ticketNumber: string;
  status: string;
  priority: string;
  latitude: number | null;
  longitude: number | null;
  area: { name: string } | null;
}

interface DistanceResult {
  distance: number;
  unit: string;
  from: { lat: number; lon: number; label?: string };
  to: { lat: number; lon: number; label?: string };
}

const STATUS_COLORS: Record<string, string> = {
  pending: '#eab308',
  assigned: '#3b82f6',
  in_progress: '#f97316',
  resolved: '#10b981',
  closed: '#6b7280',
};

export default function GISMap() {
  const { t } = useTranslation();
  const [areas, setAreas] = useState<AreaLocation[]>([]);
  const [complaints, setComplaints] = useState<TaskLocation[]>([]);
  const [loading, setLoading] = useState(true);
  const [distanceResult, setDistanceResult] = useState<DistanceResult | null>(null);
  const [calcLoading, setCalcLoading] = useState(false);

  // Distance calculator fields
  const [fromAreaId, setFromAreaId] = useState('');
  const [toComplaintId, setToComplaintId] = useState('');
  const [lat1, setLat1] = useState('');
  const [lon1, setLon1] = useState('');
  const [lat2, setLat2] = useState('');
  const [lon2, setLon2] = useState('');

  // Task distance lookup
  const [complaintLookupId, setComplaintLookupId] = useState('');
  const [complaintDistance, setComplaintDistance] = useState<DistanceResult | null>(null);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await authFetch('/api/gis');
      if (res.ok) {
        const data = await res.json();
        setAreas(data.areas || []);
        setComplaints(data.complaints || []);
      }
    } catch { } finally { setLoading(false); }
  }, []);

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

  const calculateDistance = async () => {
    if (!lat1 || !lon1 || !lat2 || !lon2) return;
    setCalcLoading(true);
    try {
      const res = await authFetch(`/api/gis?lat1=${lat1}&lon1=${lon1}&lat2=${lat2}&lon2=${lon2}`);
      if (res.ok) {
        const data = await res.json();
        setDistanceResult(data);
      }
    } catch { } finally { setCalcLoading(false); }
  };

  const calculateAreaToComplaint = async () => {
    if (!fromAreaId) return;
    const fromArea = areas.find(a => a.id === fromAreaId);
    if (!fromArea?.latitude || !fromArea?.longitude) {
      // Use API for complaint-based calculation
    }

    setCalcLoading(true);
    try {
      if (toComplaintId) {
        const complaint = complaints.find(c => c.id === toComplaintId);
        if (fromArea?.latitude && fromArea?.longitude && complaint?.latitude && complaint?.longitude) {
          const res = await authFetch(`/api/gis?lat1=${fromArea.latitude}&lon1=${fromArea.longitude}&lat2=${complaint.latitude}&lon2=${complaint.longitude}`);
          if (res.ok) {
            const data = await res.json();
            setDistanceResult({
              ...data,
              from: { ...data.from, label: fromArea.name },
              to: { ...data.to, label: `Task ${complaint.ticketNumber}` },
            });
          }
        }
      } else if (lat2 && lon2 && fromArea?.latitude && fromArea?.longitude) {
        const res = await authFetch(`/api/gis?lat1=${fromArea.latitude}&lon1=${fromArea.longitude}&lat2=${lat2}&lon2=${lon2}`);
        if (res.ok) {
          const data = await res.json();
          setDistanceResult({ ...data, from: { ...data.from, label: fromArea.name } });
        }
      }
    } catch { } finally { setCalcLoading(false); }
  };

  // Task distance lookup function
  const lookupComplaintDistance = async () => {
    if (!complaintLookupId) return;
    setCalcLoading(true);
    try {
      const res = await authFetch(`/api/gis?complaintId=${complaintLookupId}`);
      if (res.ok) {
        const data = await res.json();
        setComplaintDistance(data);
      }
    } catch { } finally { setCalcLoading(false); }
  };

  const areasWithCoords = areas.filter(a => a.latitude && a.longitude);
  const complaintsWithCoords = complaints.filter(c => c.latitude && c.longitude);

  // Generate OpenStreetMap iframe URL with multiple markers
  const getMapUrl = () => {
    if (areasWithCoords.length === 0) return null;

    const centerLat = areasWithCoords.reduce((sum, a) => sum + (a.latitude || 0), 0) / areasWithCoords.length;
    const centerLon = areasWithCoords.reduce((sum, a) => sum + (a.longitude || 0), 0) / areasWithCoords.length;

    // Calculate bbox for all markers
    const lats = areasWithCoords.map(a => a.latitude || 0);
    const lons = areasWithCoords.map(a => a.longitude || 0);
    const minLat = Math.min(...lats) - 0.02;
    const maxLat = Math.max(...lats) + 0.02;
    const minLon = Math.min(...lons) - 0.02;
    const maxLon = Math.max(...lons) + 0.02;

    // Use OSM embed with marker for center and bbox
    const marker = `${centerLat},${centerLon}`;
    return `https://www.openstreetmap.org/export/embed.html?bbox=${minLon},${minLat},${maxLon},${maxLat}&layer=mapnik&marker=${marker}`;
  };

  if (loading) {
    return <div className="flex items-center justify-center py-20"><Loader2 className="w-8 h-8 animate-spin text-emerald-600" /></div>;
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground">GIS Tracking</h1>
        <p className="text-sm text-muted-foreground mt-1">Track area locations on map and calculate distances</p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Map View */}
        <Card className="lg:col-span-2">
          <CardHeader className="pb-2">
            <CardTitle className="text-base flex items-center gap-2">
              <MapPin className="w-4 h-4 text-emerald-600" />
              Area Locations Map
            </CardTitle>
            <CardDescription>
              Geographic distribution of service areas ({areasWithCoords.length} areas with coordinates)
            </CardDescription>
          </CardHeader>
          <CardContent>
            {areasWithCoords.length > 0 ? (
              <div className="w-full h-96 rounded-lg border border-emerald-200 overflow-hidden bg-emerald-50 relative">
                <iframe
                  title="Area Map"
                  width="100%"
                  height="100%"
                  frameBorder="0"
                  scrolling="no"
                  src={getMapUrl() || ''}
                  className="w-full h-full"
                />
                {/* Marker Legend */}
                <div className="absolute bottom-2 right-2 bg-white/90 dark:bg-card/90 rounded-lg p-2 text-xs space-y-1 backdrop-blur-sm border">
                  <p className="font-semibold text-[10px]">Area Markers ({areasWithCoords.length})</p>
                  {areasWithCoords.slice(0, 8).map(area => (
                    <div key={area.id} className="flex items-center gap-1.5">
                      <div className="w-2.5 h-2.5 rounded-full bg-emerald-500" />
                      <span className="text-[10px]">{area.name} ({area.latitude?.toFixed(3)}, {area.longitude?.toFixed(3)})</span>
                    </div>
                  ))}
                  {areasWithCoords.length > 8 && (
                    <p className="text-[10px] text-muted-foreground">+{areasWithCoords.length - 8} more</p>
                  )}
                </div>
                {/* Task markers legend */}
                {complaintsWithCoords.length > 0 && (
                  <div className="absolute top-2 right-2 bg-white/90 dark:bg-card/90 rounded-lg p-2 text-xs space-y-1 backdrop-blur-sm border">
                    <p className="font-semibold text-[10px]">Tasks by Status ({complaintsWithCoords.length})</p>
                    {Object.entries(STATUS_COLORS).map(([status, color]) => {
                      const count = complaintsWithCoords.filter(c => c.status === status).length;
                      if (count === 0) return null;
                      return (
                        <div key={status} className="flex items-center gap-1.5">
                          <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: color }} />
                          <span className="text-[10px] capitalize">{status}: {count}</span>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            ) : (
              <div className="h-96 rounded-lg border border-dashed border-emerald-200 flex items-center justify-center bg-emerald-50/30">
                <div className="text-center">
                  <MapPin className="w-12 h-12 mx-auto mb-3 text-emerald-300" />
                  <p className="text-sm text-muted-foreground">No areas with coordinates configured</p>
                  <p className="text-xs text-muted-foreground mt-1">Add latitude/longitude to areas to see them on the map</p>
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Area Coordinates Table */}
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-base flex items-center gap-2">
              <Navigation className="w-4 h-4 text-emerald-600" />
              Area Coordinates
            </CardTitle>
            <CardDescription>{areasWithCoords.length} of {areas.length} areas have coordinates</CardDescription>
          </CardHeader>
          <CardContent>
            {areasWithCoords.length > 0 ? (
              <div className="max-h-72 overflow-y-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="text-xs">Area</TableHead>
                      <TableHead className="text-xs">Lat</TableHead>
                      <TableHead className="text-xs">Lon</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {areasWithCoords.map(area => (
                      <TableRow key={area.id} className="cursor-pointer" onClick={() => {
                        setLat1(String(area.latitude));
                        setLon1(String(area.longitude));
                      }}>
                        <TableCell className="text-xs font-medium">{area.name}</TableCell>
                        <TableCell className="text-xs font-mono">{area.latitude?.toFixed(4)}</TableCell>
                        <TableCell className="text-xs font-mono">{area.longitude?.toFixed(4)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <p className="text-sm text-muted-foreground text-center py-8">{t.common.noData}</p>
            )}
          </CardContent>
        </Card>

        {/* Area-to-Task Distance Calculator */}
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-base flex items-center gap-2">
              <Ruler className="w-4 h-4 text-emerald-600" />
              Distance Calculator
            </CardTitle>
            <CardDescription>Calculate distance between areas and tasks</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Quick: Area to Area */}
            <div className="space-y-3">
              <Label className="text-xs font-medium">From Area</Label>
              <Select value={fromAreaId} onValueChange={(v) => {
                setFromAreaId(v);
                const area = areas.find(a => a.id === v);
                if (area?.latitude && area?.longitude) {
                  setLat1(String(area.latitude));
                  setLon1(String(area.longitude));
                }
              }}>
                <SelectTrigger><SelectValue placeholder="Select from area" /></SelectTrigger>
                <SelectContent>
                  {areasWithCoords.map(area => (
                    <SelectItem key={area.id} value={area.id}>{area.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Manual coordinates */}
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label className="text-xs">From Lat</Label>
                <Input type="number" step="0.0001" value={lat1} onChange={(e) => setLat1(e.target.value)} placeholder="23.8103" />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs">From Lon</Label>
                <Input type="number" step="0.0001" value={lon1} onChange={(e) => setLon1(e.target.value)} placeholder="90.4125" />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label className="text-xs">To Lat</Label>
                <Input type="number" step="0.0001" value={lat2} onChange={(e) => setLat2(e.target.value)} placeholder="23.7806" />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs">To Lon</Label>
                <Input type="number" step="0.0001" value={lon2} onChange={(e) => setLon2(e.target.value)} placeholder="90.3987" />
              </div>
            </div>

            {/* Quick fill buttons */}
            {areasWithCoords.length > 0 && (
              <div className="space-y-1.5">
                <Label className="text-xs text-muted-foreground">Quick fill from areas:</Label>
                <div className="flex flex-wrap gap-1.5">
                  {areasWithCoords.slice(0, 8).map(area => (
                    <button
                      key={area.id}
                      onClick={() => {
                        if (!lat1 || !lon1) {
                          setLat1(String(area.latitude));
                          setLon1(String(area.longitude));
                        } else {
                          setLat2(String(area.latitude));
                          setLon2(String(area.longitude));
                        }
                      }}
                      className="text-xs px-2 py-1 rounded-full bg-emerald-50 dark:bg-emerald-950/30 text-emerald-700 dark:text-emerald-300 hover:bg-emerald-100 transition-colors"
                    >
                      {area.name}
                    </button>
                  ))}
                </div>
              </div>
            )}

            <Button className="w-full bg-emerald-600 hover:bg-emerald-700" onClick={calculateDistance} disabled={calcLoading || !lat1 || !lon1 || !lat2 || !lon2}>
              {calcLoading ? <Loader2 className="w-4 h-4 animate-spin mr-1" /> : <Ruler className="w-4 h-4 mr-1" />}
              Calculate Distance
            </Button>

            {distanceResult && (
              <div className="bg-emerald-50 dark:bg-emerald-950/30 rounded-lg p-4 border border-emerald-200">
                <div className="text-center">
                  <p className="text-3xl font-bold text-emerald-700">{distanceResult.distance}</p>
                  <p className="text-sm text-emerald-600">{distanceResult.unit}</p>
                </div>
                <div className="mt-3 space-y-1 text-xs text-muted-foreground">
                  <p>From: {distanceResult.from.lat.toFixed(4)}, {distanceResult.from.lon.toFixed(4)} {distanceResult.from.label ? `(${distanceResult.from.label})` : ''}</p>
                  <p>To: {distanceResult.to.lat.toFixed(4)}, {distanceResult.to.lon.toFixed(4)} {distanceResult.to.label ? `(${distanceResult.to.label})` : ''}</p>
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Task Distance Lookup */}
        <Card className="lg:col-span-2">
          <CardHeader className="pb-2">
            <CardTitle className="text-base flex items-center gap-2">
              <Info className="w-4 h-4 text-emerald-600" />
              Task Distance Lookup
            </CardTitle>
            <CardDescription>Calculate distance from HOD area to task location (uses area center if task has no coordinates)</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 items-end">
              <div className="space-y-1.5">
                <Label className="text-xs">Select Task</Label>
                <Select value={complaintLookupId} onValueChange={setComplaintLookupId}>
                  <SelectTrigger><SelectValue placeholder="Select a task" /></SelectTrigger>
                  <SelectContent>
                    {complaints.slice(0, 50).map(c => (
                      <SelectItem key={c.id} value={c.id}>
                        {c.ticketNumber} - {c.area?.name || 'No Area'} ({c.status})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <Button
                onClick={lookupComplaintDistance}
                disabled={!complaintLookupId || calcLoading}
                className="bg-emerald-600 hover:bg-emerald-700"
              >
                {calcLoading ? <Loader2 className="w-4 h-4 animate-spin mr-1" /> : <Ruler className="w-4 h-4 mr-1" />}
                Calculate HOD Distance
              </Button>
            </div>

            {complaintDistance && (
              <div className="bg-emerald-50 dark:bg-emerald-950/30 rounded-lg p-4 border border-emerald-200">
                {complaintDistance.distance !== null ? (
                  <>
                    <div className="text-center">
                      <p className="text-3xl font-bold text-emerald-700">{complaintDistance.distance}</p>
                      <p className="text-sm text-emerald-600">{complaintDistance.unit}</p>
                    </div>
                    <div className="mt-3 space-y-1 text-xs text-muted-foreground">
                      <p>From: {complaintDistance.from.lat.toFixed(4)}, {complaintDistance.from.lon.toFixed(4)} {complaintDistance.from.label ? `(${complaintDistance.from.label})` : ''}</p>
                      <p>To: {complaintDistance.to.lat.toFixed(4)}, {complaintDistance.to.lon.toFixed(4)} {complaintDistance.to.label ? `(${complaintDistance.to.label})` : ''}</p>
                    </div>
                  </>
                ) : (
                  <div className="text-center">
                    <p className="text-sm text-orange-600">{complaintDistance.error || 'Missing coordinates for distance calculation'}</p>
                    <p className="text-xs text-muted-foreground mt-1">
                      Ensure both the task area and HOD area have coordinates configured.
                    </p>
                  </div>
                )}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
