
import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import { User, Mail, Phone, MapPin, Award, Star, Edit, Camera, Upload } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";

export default function WorkforceProfile() {
  const [showUploadDialog, setShowUploadDialog] = useState(false);
  const [uploading, setUploading] = useState(false);
  const queryClient = useQueryClient();
  const { toast } = useToast();

  const { data: user } = useQuery({
    queryKey: ['current-user'],
    queryFn: () => base44.auth.me(),
  });

  // Sample avatar if user doesn't have one
  const sampleAvatar = "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=400&h=400&fit=crop";
  const userAvatar = user?.profile_picture || sampleAvatar;

  const updateProfilePictureMutation = useMutation({
    mutationFn: (profilePictureUrl) => base44.auth.updateMe({ profile_picture: profilePictureUrl }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['current-user'] });
      toast({
        title: "Profile Picture Updated",
        description: "Your profile picture has been updated successfully",
      });
      setShowUploadDialog(false);
    },
  });

  const handleFileUpload = async (event) => {
    const file = event.target.files?.[0];
    if (!file) return;

    // Validate file type
    if (!file.type.startsWith('image/')) {
      toast({
        title: "Invalid File",
        description: "Please upload an image file",
        variant: "destructive",
      });
      return;
    }

    // Validate file size (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      toast({
        title: "File Too Large",
        description: "Please upload an image smaller than 5MB",
        variant: "destructive",
      });
      return;
    }

    setUploading(true);
    try {
      const { file_url } = await base44.integrations.Core.UploadFile({ file });
      await updateProfilePictureMutation.mutateAsync(file_url);
    } catch (error) {
      toast({
        title: "Upload Failed",
        description: error.message || "Failed to upload profile picture",
        variant: "destructive",
      });
    } finally {
      setUploading(false);
    }
  };

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-4xl mx-auto">
        <div className="mb-6">
          <h1 className="text-3xl font-bold text-[#1C323E]">My Profile</h1>
          <p className="text-slate-500 mt-1">Manage your personal information and certifications</p>
        </div>

        {/* Profile Card */}
        <Card className="mb-8 border-slate-200">
          <CardContent className="p-8">
            <div className="flex items-start justify-between mb-6">
              <div className="flex items-center gap-6">
                <div className="relative">
                  <Avatar className="w-24 h-24 border-4 border-white shadow-lg">
                    <AvatarImage src={userAvatar} alt={user?.full_name} />
                    <AvatarFallback className="bg-gradient-to-br from-[#0A39DF] to-[#1C323E] text-white text-3xl font-bold">
                      {user?.full_name?.charAt(0) || user?.email?.charAt(0) || '?'}
                    </AvatarFallback>
                  </Avatar>
                  <button
                    onClick={() => setShowUploadDialog(true)}
                    className="absolute bottom-0 right-0 w-8 h-8 bg-[#0A39DF] hover:bg-[#0A39DF]/90 text-white rounded-full flex items-center justify-center shadow-lg transition-all"
                    title="Change profile picture"
                  >
                    <Camera className="w-4 h-4" />
                  </button>
                </div>
                <div>
                  <h2 className="text-2xl font-bold text-[#1C323E] mb-2">{user?.full_name || 'User'}</h2>
                  <Badge className="bg-blue-100 text-blue-700 mb-2">Workforce</Badge>
                  <div className="flex items-center gap-2 text-sm text-slate-600">
                    <Star className="w-4 h-4 text-amber-500 fill-amber-500" />
                    <span className="font-semibold">4.8 Rating</span>
                    <span className="text-slate-400">•</span>
                    <span>127 completed shifts</span>
                  </div>
                </div>
              </div>
              <Button variant="outline">
                <Edit className="w-4 h-4 mr-2" />
                Edit Profile
              </Button>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="flex items-center gap-3 p-4 bg-slate-50 rounded-lg">
                <Mail className="w-5 h-5 text-[#0A39DF]" />
                <div>
                  <p className="text-xs text-slate-500">Email</p>
                  <p className="font-medium text-slate-700">{user?.email}</p>
                </div>
              </div>

              <div className="flex items-center gap-3 p-4 bg-slate-50 rounded-lg">
                <Phone className="w-5 h-5 text-[#0A39DF]" />
                <div>
                  <p className="text-xs text-slate-500">Phone</p>
                  <p className="font-medium text-slate-700">{user?.phone || 'Not provided'}</p>
                </div>
              </div>

              <div className="flex items-center gap-3 p-4 bg-slate-50 rounded-lg md:col-span-2">
                <MapPin className="w-5 h-5 text-[#0A39DF]" />
                <div>
                  <p className="text-xs text-slate-500">Location</p>
                  <p className="font-medium text-slate-700">San Francisco, CA</p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Certifications */}
        <Card className="mb-8 border-slate-200">
          <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b">
            <CardTitle className="flex items-center gap-2">
              <Award className="w-5 h-5 text-[#0A39DF]" />
              Certifications & Training
            </CardTitle>
          </CardHeader>
          <CardContent className="p-6">
            <div className="space-y-4">
              {[
                { name: "Food Handler Certificate", status: "Valid", expiry: "Dec 2025" },
                { name: "ServSafe Alcohol", status: "Valid", expiry: "Mar 2026" },
                { name: "First Aid & CPR", status: "Valid", expiry: "Aug 2025" },
              ].map((cert, index) => (
                <div key={index} className="flex items-center justify-between p-4 bg-slate-50 rounded-lg">
                  <div>
                    <h4 className="font-semibold text-[#1C323E]">{cert.name}</h4>
                    <p className="text-sm text-slate-500 mt-1">Expires: {cert.expiry}</p>
                  </div>
                  <Badge className="bg-green-100 text-green-700">{cert.status}</Badge>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Performance Stats */}
        <Card className="border-slate-200">
          <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b">
            <CardTitle>Performance Summary</CardTitle>
          </CardHeader>
          <CardContent className="p-6">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center p-4">
                <p className="text-3xl font-bold text-[#0A39DF]">97%</p>
                <p className="text-sm text-slate-500 mt-1">Attendance Rate</p>
              </div>
              <div className="text-center p-4">
                <p className="text-3xl font-bold text-green-600">4.8</p>
                <p className="text-sm text-slate-500 mt-1">Avg Rating</p>
              </div>
              <div className="text-center p-4">
                <p className="text-3xl font-bold text-blue-600">127</p>
                <p className="text-sm text-slate-500 mt-1">Total Shifts</p>
              </div>
              <div className="text-center p-4">
                <p className="text-3xl font-bold text-purple-600">0</p>
                <p className="text-sm text-slate-500 mt-1">Cancellations</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Upload Profile Picture Dialog */}
      <Dialog open={showUploadDialog} onOpenChange={setShowUploadDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Change Profile Picture</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="flex flex-col items-center gap-4 p-6 border-2 border-dashed border-slate-300 rounded-lg">
              <Avatar className="w-32 h-32">
                <AvatarImage src={userAvatar} />
                <AvatarFallback className="bg-gradient-to-br from-[#0A39DF] to-[#1C323E] text-white text-4xl font-bold">
                  {user?.full_name?.charAt(0) || user?.email?.charAt(0) || '?'}
                </AvatarFallback>
              </Avatar>
              <div className="text-center">
                <label htmlFor="file-upload" className="cursor-pointer">
                  <div className="flex items-center gap-2 px-4 py-2 bg-[#0A39DF] hover:bg-[#0A39DF]/90 text-white rounded-lg transition-colors">
                    <Upload className="w-4 h-4" />
                    <span>{uploading ? 'Uploading...' : 'Choose Image'}</span>
                  </div>
                  <input
                    id="file-upload"
                    type="file"
                    accept="image/*"
                    className="hidden"
                    onChange={handleFileUpload}
                    disabled={uploading}
                  />
                </label>
                <p className="text-xs text-slate-500 mt-2">PNG, JPG or GIF • Max 5MB</p>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowUploadDialog(false)} disabled={uploading}>
              Cancel
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
