/**
 * POI Context View Component
 *
 * Main view for POI detection results and management
 * Displays map, summary, and detailed category information
 */

import React, { useState, useEffect } from 'react';
import { Card, CardHeader, CardContent, CardTitle, CardDescription } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Alert, AlertDescription } from '@/components/ui/Alert';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/Tabs';
import { RefreshCw, AlertCircle, CheckCircle, MapPin } from 'lucide-react';
import { POIMap } from './POIMap';
import { POISummaryCard } from './POISummaryCard';
import { POICategoryAccordion } from './POICategoryAccordion';
import { usePOIContext } from '@/hooks/usePOIContext';
import { Loader } from '@/components/ui/Loader';

interface POIContextViewProps {
  tenantId: string;
  bakeryLocation?: {
    latitude: number;
    longitude: number;
  };
}

export const POIContextView: React.FC<POIContextViewProps> = ({
  tenantId,
  bakeryLocation
}) => {
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState('overview');

  const {
    poiContext,
    isLoading,
    isRefreshing,
    error,
    isStale,
    needsRefresh,
    competitorAnalysis,
    competitiveInsights,
    detectPOIs,
    refreshPOIs,
    fetchContext,
    fetchCompetitorAnalysis
  } = usePOIContext({ tenantId, autoFetch: true });

  // Fetch competitor analysis when POI context is available
  useEffect(() => {
    if (poiContext && !competitorAnalysis) {
      fetchCompetitorAnalysis();
    }
  }, [poiContext, competitorAnalysis, fetchCompetitorAnalysis]);

  // Handle initial POI detection if no context exists
  const handleInitialDetection = async () => {
    if (!bakeryLocation) {
      return;
    }
    await detectPOIs(bakeryLocation.latitude, bakeryLocation.longitude);
  };

  // Handle POI refresh
  const handleRefresh = async () => {
    await refreshPOIs();
  };

  if (isLoading && !poiContext) {
    return (
      <Card>
        <CardContent className="py-12">
          <Loader size="large" text="Loading POI context..." />
        </CardContent>
      </Card>
    );
  }

  // No POI context - show detection prompt
  if (!poiContext && !error) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <MapPin className="h-5 w-5" />
            Location Context
          </CardTitle>
          <CardDescription>
            Detect nearby points of interest to enhance demand forecasting accuracy
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <Alert>
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>
              POI detection has not been run for this location. Click the button below to
              automatically detect nearby schools, offices, transport hubs, and other
              points of interest that may affect bakery demand.
            </AlertDescription>
          </Alert>

          {bakeryLocation && (
            <div className="p-4 bg-gray-50 rounded-lg">
              <div className="text-sm font-medium text-gray-700 mb-2">
                Bakery Location
              </div>
              <div className="text-sm text-gray-600">
                Latitude: {bakeryLocation.latitude.toFixed(6)}
              </div>
              <div className="text-sm text-gray-600">
                Longitude: {bakeryLocation.longitude.toFixed(6)}
              </div>
            </div>
          )}

          <Button
            onClick={handleInitialDetection}
            disabled={!bakeryLocation || isLoading}
            size="lg"
            className="w-full"
          >
            {isLoading ? (
              <>
                <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                Detecting POIs...
              </>
            ) : (
              <>
                <MapPin className="mr-2 h-4 w-4" />
                Detect Points of Interest
              </>
            )}
          </Button>

          {!bakeryLocation && (
            <Alert variant="warning">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>
                Bakery location is required for POI detection. Please ensure your
                bakery address has been geocoded.
              </AlertDescription>
            </Alert>
          )}
        </CardContent>
      </Card>
    );
  }

  // Error state
  if (error && !poiContext) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-red-600">
            <AlertCircle className="h-5 w-5" />
            Error Loading POI Context
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Alert variant="destructive">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
          <Button onClick={fetchContext} className="mt-4">
            Retry
          </Button>
        </CardContent>
      </Card>
    );
  }

  if (!poiContext) return null;

  return (
    <div className="space-y-6">
      {/* Header */}
      <Card>
        <CardHeader>
          <div className="flex items-start justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <MapPin className="h-5 w-5" />
                Location Context & POI Analysis
              </CardTitle>
              <CardDescription>
                Detected {poiContext.total_pois_detected} points of interest around your bakery
              </CardDescription>
            </div>
            <div className="flex gap-2">
              {(isStale || needsRefresh) && (
                <Alert variant="warning" className="mb-0">
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription className="text-xs">
                    POI data may be outdated
                  </AlertDescription>
                </Alert>
              )}
              <Button
                onClick={handleRefresh}
                disabled={isRefreshing}
                variant="outline"
                size="sm"
              >
                {isRefreshing ? (
                  <>
                    <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                    Refreshing...
                  </>
                ) : (
                  <>
                    <RefreshCw className="mr-2 h-4 w-4" />
                    Refresh POI Data
                  </>
                )}
              </Button>
            </div>
          </div>
        </CardHeader>
      </Card>

      {/* Competitive Insights */}
      {competitiveInsights && competitiveInsights.length > 0 && (
        <Alert>
          <CheckCircle className="h-4 w-4" />
          <AlertDescription>
            <div className="font-semibold mb-2">Competitive Analysis</div>
            <ul className="space-y-1 text-sm">
              {competitiveInsights.map((insight, index) => (
                <li key={index}>{insight}</li>
              ))}
            </ul>
          </AlertDescription>
        </Alert>
      )}

      {/* Main Content */}
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="overview">Overview & Map</TabsTrigger>
          <TabsTrigger value="categories">Detailed Categories</TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
            {/* Map */}
            <div className="lg:col-span-2 h-[600px]">
              <POIMap
                poiContext={poiContext}
                selectedCategory={selectedCategory}
              />
            </div>

            {/* Summary */}
            <div className="lg:col-span-1">
              <POISummaryCard
                poiContext={poiContext}
                onCategorySelect={setSelectedCategory}
              />
            </div>
          </div>
        </TabsContent>

        <TabsContent value="categories" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>POI Categories</CardTitle>
              <CardDescription>
                Detailed breakdown of detected points of interest by category
              </CardDescription>
            </CardHeader>
            <CardContent>
              <POICategoryAccordion
                poiContext={poiContext}
                selectedCategory={selectedCategory}
                onCategorySelect={setSelectedCategory}
              />
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Detection Metadata */}
      <Card>
        <CardHeader>
          <CardTitle className="text-sm">Detection Metadata</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            <div>
              <div className="text-gray-600">Detection Date</div>
              <div className="font-medium">
                {new Date(poiContext.detection_timestamp).toLocaleDateString()}
              </div>
            </div>
            <div>
              <div className="text-gray-600">Source</div>
              <div className="font-medium capitalize">{poiContext.detection_source}</div>
            </div>
            <div>
              <div className="text-gray-600">Relevant Categories</div>
              <div className="font-medium">{poiContext.relevant_categories?.length || 0}</div>
            </div>
            <div>
              <div className="text-gray-600">ML Features</div>
              <div className="font-medium">
                {Object.keys(poiContext.ml_features || {}).length}
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
};
