
'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { CheckCircle2, Clock, AlertCircle, Upload, MapPin } from 'lucide-react';
import { toast } from 'sonner';

interface Milestone {
  id: string;
  milestone: string;
  title: string;
  description: string;
  status: string;
  photosRequired: boolean;
  minPhotos: number;
  photosUploaded: number;
  gpsRequired: boolean;
  locationVerified: boolean;
  paymentAmount: number | null;
  paymentReleased: boolean;
  targetDate: string | null;
  actualDate: string | null;
}

interface MilestoneTrackerProps {
  contractId: string;
  canEdit?: boolean;
}

export function MilestoneTracker({ contractId, canEdit = false }: MilestoneTrackerProps) {
  const [milestones, setMilestones] = useState<Milestone[]>([]);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState<string | null>(null);

  useEffect(() => {
    fetchMilestones();
  }, [contractId]);

  const fetchMilestones = async () => {
    try {
      const res = await fetch(`/api/milestones/${contractId}`);
      const data = await res.json();
      setMilestones(data);
    } catch (error) {
      console.error('Error fetching milestones:', error);
    } finally {
      setLoading(false);
    }
  };

  const handlePhotoUpload = async (milestoneId: string, file: File) => {
    setUploading(milestoneId);
    try {
      // Get GPS location
      if (!navigator.geolocation) {
        toast.error('Geolocation is not supported by your browser');
        return;
      }

      navigator.geolocation.getCurrentPosition(
        async (position) => {
          const formData = new FormData();
          formData.append('file', file);
          formData.append('milestoneId', milestoneId);
          formData.append('contractId', contractId);
          formData.append('latitude', position.coords.latitude.toString());
          formData.append('longitude', position.coords.longitude.toString());
          formData.append('accuracy', position.coords.accuracy.toString());

          const res = await fetch('/api/uploads/milestone-photo', {
            method: 'POST',
            body: formData,
          });

          if (res.ok) {
            const data = await res.json();
            toast.success(
              data.locationVerified
                ? 'Photo uploaded and location verified!'
                : 'Photo uploaded (location not verified)'
            );
            fetchMilestones();
          } else {
            toast.error('Failed to upload photo');
          }
        },
        (error) => {
          toast.error('Failed to get GPS location. Please enable location services.');
        },
        { enableHighAccuracy: true }
      );
    } catch (error) {
      console.error('Error uploading photo:', error);
      toast.error('Failed to upload photo');
    } finally {
      setUploading(null);
    }
  };

  const updateMilestoneStatus = async (milestoneId: string, status: string) => {
    try {
      const res = await fetch(`/api/milestones/${contractId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ milestoneId, status }),
      });

      if (res.ok) {
        toast.success('Milestone updated');
        fetchMilestones();
      }
    } catch (error) {
      console.error('Error updating milestone:', error);
      toast.error('Failed to update milestone');
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'COMPLETED':
        return <CheckCircle2 className="w-5 h-5 text-green-500" />;
      case 'IN_PROGRESS':
        return <Clock className="w-5 h-5 text-blue-500" />;
      case 'DELAYED':
      case 'BLOCKED':
        return <AlertCircle className="w-5 h-5 text-red-500" />;
      default:
        return <Clock className="w-5 h-5 text-gray-400" />;
    }
  };

  const getStatusBadge = (status: string) => {
    const variants: any = {
      PENDING: 'secondary',
      IN_PROGRESS: 'default',
      COMPLETED: 'success',
      DELAYED: 'destructive',
      BLOCKED: 'destructive',
    };
    return <Badge variant={variants[status] || 'secondary'}>{status}</Badge>;
  };

  const completedMilestones = milestones.filter((m) => m.status === 'COMPLETED').length;
  const progressPercent = milestones.length > 0 ? (completedMilestones / milestones.length) * 100 : 0;

  if (loading) {
    return <div>Loading milestones...</div>;
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Project Progress</CardTitle>
          <CardDescription>
            {completedMilestones} of {milestones.length} milestones completed
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Progress value={progressPercent} className="w-full" />
        </CardContent>
      </Card>

      <div className="space-y-4">
        {milestones.map((milestone, index) => (
          <Card key={milestone.id}>
            <CardHeader>
              <div className="flex items-start justify-between">
                <div className="flex items-center gap-3">
                  {getStatusIcon(milestone.status)}
                  <div>
                    <CardTitle className="text-lg">{milestone.title}</CardTitle>
                    {milestone.description && (
                      <CardDescription>{milestone.description}</CardDescription>
                    )}
                  </div>
                </div>
                {getStatusBadge(milestone.status)}
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* Photo Requirements */}
              {milestone.photosRequired && (
                <div className="space-y-2">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground">
                      Photos: {milestone.photosUploaded} / {milestone.minPhotos}
                    </span>
                    {milestone.photosUploaded >= milestone.minPhotos && (
                      <Badge variant="success">Requirements Met</Badge>
                    )}
                  </div>
                  {canEdit && milestone.photosUploaded < milestone.minPhotos && (
                    <div>
                      <input
                        type="file"
                        accept="image/*"
                        capture="environment"
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          if (file) handlePhotoUpload(milestone.id, file);
                        }}
                        disabled={uploading === milestone.id}
                        className="hidden"
                        id={`photo-${milestone.id}`}
                      />
                      <label htmlFor={`photo-${milestone.id}`}>
                        <Button
                          variant="outline"
                          size="sm"
                          disabled={uploading === milestone.id}
                          asChild
                        >
                          <span>
                            <Upload className="w-4 h-4 mr-2" />
                            {uploading === milestone.id ? 'Uploading...' : 'Upload Photo'}
                          </span>
                        </Button>
                      </label>
                    </div>
                  )}
                </div>
              )}

              {/* GPS Requirements */}
              {milestone.gpsRequired && (
                <div className="flex items-center gap-2 text-sm">
                  <MapPin className="w-4 h-4" />
                  <span className="text-muted-foreground">GPS Location Required</span>
                  {milestone.locationVerified && (
                    <Badge variant="success">Verified</Badge>
                  )}
                </div>
              )}

              {/* Payment Info */}
              {milestone.paymentAmount && (
                <div className="flex items-center justify-between text-sm bg-muted p-3 rounded-md">
                  <span>Payment Amount: ${milestone.paymentAmount.toLocaleString()}</span>
                  {milestone.paymentReleased && (
                    <Badge variant="success">Released</Badge>
                  )}
                </div>
              )}

              {/* Actions */}
              {canEdit && milestone.status !== 'COMPLETED' && (
                <div className="flex gap-2">
                  {milestone.status === 'PENDING' && (
                    <Button
                      size="sm"
                      onClick={() => updateMilestoneStatus(milestone.id, 'IN_PROGRESS')}
                    >
                      Start Milestone
                    </Button>
                  )}
                  {milestone.status === 'IN_PROGRESS' &&
                    (!milestone.photosRequired ||
                      milestone.photosUploaded >= milestone.minPhotos) &&
                    (!milestone.gpsRequired || milestone.locationVerified) && (
                      <Button
                        size="sm"
                        variant="default"
                        onClick={() => updateMilestoneStatus(milestone.id, 'COMPLETED')}
                      >
                        Mark Complete
                      </Button>
                    )}
                </div>
              )}
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}
