import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Loading } from '@/components/Loading';
import {
  User,
  Phone,
  Save,
  CheckCircle,
  AlertCircle,
  MapPin,
  Navigation,
  Route,
  Gauge,
  Car,
  Clock,
  Shield,
} from 'lucide-react';
import toast from 'react-hot-toast';
import { useMyGpsStatus, useMyGpsStats, useUpdateGpsConsent } from '@/hooks/useGps';
import { formatDistanceToNow } from 'date-fns';

interface DriverProfileData {
  id: string;
  name: string;
  phone: string | null;
  department: string | null;
  isAvailable: boolean;
  user: {
    email: string;
    picture: string | null;
  } | null;
}

export function DriverProfile() {
  const queryClient = useQueryClient();
  const [phone, setPhone] = useState('');
  const [isEditing, setIsEditing] = useState(false);

  const { data: profile, isLoading, error } = useQuery<DriverProfileData>({
    queryKey: ['my-driver-profile'],
    queryFn: async () => {
      const { data } = await api.get('/drivers/me');
      return data;
    },
  });

  // Set phone when profile loads
  useEffect(() => {
    if (profile?.phone) {
      setPhone(profile.phone);
    }
  }, [profile?.phone]);

  const updateProfile = useMutation({
    mutationFn: async (newPhone: string) => {
      const { data } = await api.patch('/drivers/me', { phone: newPhone });
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['my-driver-profile'] });
      toast.success('Phone number updated successfully!');
      setIsEditing(false);
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.message || 'Failed to update phone number');
    },
  });

  const handleSave = () => {
    if (!phone.trim()) {
      toast.error('Please enter a valid phone number');
      return;
    }
    updateProfile.mutate(phone);
  };

  if (isLoading) {
    return <Loading message="Loading your profile..." />;
  }

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center py-12">
        <AlertCircle className="h-12 w-12 text-destructive mb-4" />
        <h2 className="text-xl font-semibold text-foreground mb-2">Profile Not Found</h2>
        <p className="text-muted-foreground">Unable to load your driver profile.</p>
      </div>
    );
  }

  if (!profile) {
    return null;
  }

  const hasPhone = !!profile.phone;

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground">My Profile</h1>
        <p className="text-muted-foreground">Manage your driver profile and contact information</p>
      </div>

      {/* Profile Card */}
      <div className="bg-card border border-border rounded-lg shadow-soft overflow-hidden">
        {/* Header with avatar */}
        <div className="bg-primary/10 px-6 py-8 flex items-center gap-4">
          {profile.user?.picture ? (
            <img
              src={profile.user.picture}
              alt={profile.name}
              className="h-20 w-20 rounded-full border-4 border-background shadow-md"
            />
          ) : (
            <div className="h-20 w-20 rounded-full bg-primary/20 flex items-center justify-center border-4 border-background shadow-md">
              <User className="h-10 w-10 text-primary" />
            </div>
          )}
          <div>
            <h2 className="text-2xl font-bold text-foreground">{profile.name}</h2>
            <p className="text-muted-foreground">{profile.user?.email}</p>
            {profile.department && (
              <span className="inline-block mt-1 px-2 py-0.5 bg-primary/20 text-primary text-xs font-medium rounded">
                {profile.department.replace(/_/g, ' ')}
              </span>
            )}
          </div>
        </div>

        {/* Phone Number Section */}
        <div className="p-6 border-t border-border">
          <div className="flex items-start justify-between gap-4">
            <div className="flex-1">
              <label className="block text-sm font-medium text-foreground mb-1">
                <Phone className="h-4 w-4 inline mr-1" />
                Phone Number
              </label>
              <p className="text-xs text-muted-foreground mb-3">
                Used for Signal notifications about your trips
              </p>

              {!hasPhone && !isEditing && (
                <div className="bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 rounded-lg p-4 mb-4">
                  <div className="flex items-center gap-2 text-amber-800 dark:text-amber-200">
                    <AlertCircle className="h-5 w-5 flex-shrink-0" />
                    <p className="text-sm font-medium">
                      Please add your phone number to receive trip notifications via Signal
                    </p>
                  </div>
                </div>
              )}

              {isEditing ? (
                <div className="flex items-center gap-2">
                  <input
                    type="tel"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    placeholder="+1 (555) 123-4567"
                    className="flex-1 px-3 py-2 bg-background border border-input rounded-lg text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                  <button
                    onClick={handleSave}
                    disabled={updateProfile.isPending}
                    className="px-4 py-2 bg-primary text-primary-foreground rounded-lg font-medium hover:bg-primary/90 disabled:opacity-50 flex items-center gap-2"
                  >
                    {updateProfile.isPending ? (
                      <span className="animate-spin">...</span>
                    ) : (
                      <Save className="h-4 w-4" />
                    )}
                    Save
                  </button>
                  <button
                    onClick={() => {
                      setPhone(profile.phone || '');
                      setIsEditing(false);
                    }}
                    className="px-4 py-2 bg-muted text-muted-foreground rounded-lg font-medium hover:bg-muted/80"
                  >
                    Cancel
                  </button>
                </div>
              ) : (
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    {hasPhone ? (
                      <>
                        <CheckCircle className="h-5 w-5 text-green-500" />
                        <span className="text-lg font-medium text-foreground">{profile.phone}</span>
                      </>
                    ) : (
                      <span className="text-muted-foreground italic">No phone number set</span>
                    )}
                  </div>
                  <button
                    onClick={() => setIsEditing(true)}
                    className="px-4 py-2 bg-primary text-primary-foreground rounded-lg font-medium hover:bg-primary/90"
                  >
                    {hasPhone ? 'Edit' : 'Add Phone'}
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Availability Status */}
        <div className="p-6 border-t border-border bg-muted/30">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="font-medium text-foreground">Availability Status</h3>
              <p className="text-sm text-muted-foreground">Your current availability for assignments</p>
            </div>
            <div className={`px-3 py-1 rounded-full text-sm font-medium ${
              profile.isAvailable
                ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                : 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400'
            }`}>
              {profile.isAvailable ? 'Available' : 'Unavailable'}
            </div>
          </div>
        </div>
      </div>

      {/* Info Card */}
      <div className="bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
        <h3 className="font-medium text-blue-800 dark:text-blue-200 mb-2">About Signal Notifications</h3>
        <p className="text-sm text-blue-700 dark:text-blue-300">
          When you're assigned to a trip, you'll receive notifications via Signal messenger:
        </p>
        <ul className="mt-2 text-sm text-blue-700 dark:text-blue-300 list-disc list-inside space-y-1">
          <li>20-minute reminder before pickup</li>
          <li>5-minute urgent reminder</li>
          <li>Trip start confirmation request</li>
        </ul>
      </div>

      {/* GPS Tracking Section */}
      <GpsStatsSection />
    </div>
  );
}

function GpsStatsSection() {
  const { data: gpsStatus, isLoading: statusLoading } = useMyGpsStatus();
  const { data: gpsStats, isLoading: statsLoading } = useMyGpsStats();
  const updateConsent = useUpdateGpsConsent();

  if (statusLoading) {
    return (
      <div className="bg-card border border-border rounded-lg shadow-soft p-6">
        <div className="flex items-center gap-2 mb-4">
          <MapPin className="h-5 w-5 text-primary" />
          <h2 className="text-lg font-semibold text-foreground">GPS Tracking</h2>
        </div>
        <Loading size="small" />
      </div>
    );
  }

  // Not enrolled
  if (!gpsStatus?.enrolled) {
    return (
      <div className="bg-card border border-border rounded-lg shadow-soft p-6">
        <div className="flex items-center gap-2 mb-4">
          <MapPin className="h-5 w-5 text-primary" />
          <h2 className="text-lg font-semibold text-foreground">GPS Tracking</h2>
        </div>
        <div className="bg-muted/50 rounded-lg p-4 text-center">
          <MapPin className="h-12 w-12 text-muted-foreground mx-auto mb-3" />
          <p className="text-muted-foreground">
            GPS tracking has not been set up for your account.
          </p>
          <p className="text-sm text-muted-foreground mt-1">
            Contact an administrator if you need GPS tracking enabled.
          </p>
        </div>
      </div>
    );
  }

  // Enrolled but consent not given
  if (!gpsStatus.consentGiven) {
    return (
      <div className="bg-card border border-border rounded-lg shadow-soft p-6">
        <div className="flex items-center gap-2 mb-4">
          <MapPin className="h-5 w-5 text-primary" />
          <h2 className="text-lg font-semibold text-foreground">GPS Tracking</h2>
        </div>

        <div className="bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 rounded-lg p-4 mb-4">
          <div className="flex items-start gap-3">
            <Shield className="h-5 w-5 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5" />
            <div>
              <h3 className="font-medium text-amber-800 dark:text-amber-200">
                Consent Required
              </h3>
              <p className="text-sm text-amber-700 dark:text-amber-300 mt-1">
                GPS tracking is set up for your account, but you need to provide consent before location tracking begins.
              </p>
              <ul className="text-sm text-amber-700 dark:text-amber-300 mt-2 space-y-1 list-disc list-inside">
                <li>Location is only tracked during shift hours (4 AM - 1 AM)</li>
                <li>You can view your own driving stats (miles, speed, etc.)</li>
                <li>Data is automatically deleted after 30 days</li>
                <li>You can revoke consent at any time</li>
              </ul>
            </div>
          </div>
        </div>

        <button
          onClick={() => updateConsent.mutate(true)}
          disabled={updateConsent.isPending}
          className="w-full px-4 py-3 bg-primary text-primary-foreground rounded-lg font-medium hover:bg-primary/90 disabled:opacity-50"
        >
          {updateConsent.isPending ? 'Processing...' : 'Accept GPS Tracking'}
        </button>
      </div>
    );
  }

  // Enrolled and consent given - show stats
  return (
    <div className="bg-card border border-border rounded-lg shadow-soft overflow-hidden">
      <div className="p-6 border-b border-border">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <MapPin className="h-5 w-5 text-primary" />
            <h2 className="text-lg font-semibold text-foreground">GPS Tracking</h2>
          </div>
          <div className="flex items-center gap-2">
            <span className={`px-2 py-1 rounded-full text-xs font-medium ${
              gpsStatus.isActive
                ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                : 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-400'
            }`}>
              {gpsStatus.isActive ? 'Active' : 'Inactive'}
            </span>
          </div>
        </div>
        {gpsStatus.lastActive && (
          <p className="text-sm text-muted-foreground mt-1">
            Last seen: {formatDistanceToNow(new Date(gpsStatus.lastActive), { addSuffix: true })}
          </p>
        )}
      </div>

      {/* Stats Grid */}
      {statsLoading ? (
        <div className="p-6">
          <Loading size="small" />
        </div>
      ) : gpsStats ? (
        <div className="p-6">
          <p className="text-sm text-muted-foreground mb-4">
            Stats for the last 7 days ({new Date(gpsStats.period.from).toLocaleDateString()} - {new Date(gpsStats.period.to).toLocaleDateString()})
          </p>

          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="bg-muted/50 rounded-lg p-4 text-center">
              <Route className="h-8 w-8 text-blue-500 mx-auto mb-2" />
              <p className="text-2xl font-bold text-foreground">{gpsStats.stats.totalMiles}</p>
              <p className="text-xs text-muted-foreground">Miles Driven</p>
            </div>

            <div className="bg-muted/50 rounded-lg p-4 text-center">
              <Gauge className="h-8 w-8 text-red-500 mx-auto mb-2" />
              <p className="text-2xl font-bold text-foreground">{gpsStats.stats.topSpeedMph}</p>
              <p className="text-xs text-muted-foreground">Top Speed (mph)</p>
            </div>

            <div className="bg-muted/50 rounded-lg p-4 text-center">
              <Navigation className="h-8 w-8 text-green-500 mx-auto mb-2" />
              <p className="text-2xl font-bold text-foreground">{gpsStats.stats.averageSpeedMph}</p>
              <p className="text-xs text-muted-foreground">Avg Speed (mph)</p>
            </div>

            <div className="bg-muted/50 rounded-lg p-4 text-center">
              <Car className="h-8 w-8 text-purple-500 mx-auto mb-2" />
              <p className="text-2xl font-bold text-foreground">{gpsStats.stats.totalTrips}</p>
              <p className="text-xs text-muted-foreground">Total Trips</p>
            </div>
          </div>

          {gpsStats.stats.topSpeedTimestamp && (
            <p className="text-xs text-muted-foreground mt-4 text-center">
              Top speed recorded on {new Date(gpsStats.stats.topSpeedTimestamp).toLocaleString()}
            </p>
          )}
        </div>
      ) : (
        <div className="p-6 text-center text-muted-foreground">
          <Clock className="h-8 w-8 mx-auto mb-2 opacity-50" />
          <p>No driving data available yet</p>
          <p className="text-sm">Start driving to see your stats!</p>
        </div>
      )}

      {/* Revoke Consent Option */}
      <div className="p-4 border-t border-border bg-muted/30">
        <button
          onClick={() => {
            if (confirm('Are you sure you want to revoke GPS tracking consent? Your location will no longer be tracked.')) {
              updateConsent.mutate(false);
            }
          }}
          disabled={updateConsent.isPending}
          className="text-sm text-muted-foreground hover:text-foreground transition-colors"
        >
          Revoke tracking consent
        </button>
      </div>
    </div>
  );
}
