import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useMutation, useQueryClient, useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { ArrowLeft, Save, Upload, Users } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";

export default function CreateTeam() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { toast } = useToast();

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

  const [formData, setFormData] = useState({
    team_name: "",
    full_name: user?.full_name || "",
    email: user?.email || "",
    phone: user?.phone || "",
    address: user?.address || "",
    city: user?.city || "",
    zip_code: user?.zip_code || "",
    company_logo: "",
  });

  const [logoFile, setLogoFile] = useState(null);
  const [uploadingLogo, setUploadingLogo] = useState(false);

  const createTeamMutation = useMutation({
    mutationFn: (teamData) => base44.entities.Team.create(teamData),
    onSuccess: (newTeam) => {
      queryClient.invalidateQueries({ queryKey: ['teams'] });
      toast({
        title: "Team Created",
        description: "Your team has been created successfully",
      });
      navigate(createPageUrl(`TeamDetails?id=${newTeam.id}`));
    },
  });

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

    setUploadingLogo(true);
    try {
      const { file_url } = await base44.integrations.Core.UploadFile({ file });
      setFormData({ ...formData, company_logo: file_url });
      setLogoFile(file);
      toast({
        title: "Logo Uploaded",
        description: "Company logo uploaded successfully",
      });
    } catch (error) {
      toast({
        title: "Upload Failed",
        description: "Failed to upload logo",
        variant: "destructive"
      });
    } finally {
      setUploadingLogo(false);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    
    const teamData = {
      ...formData,
      owner_id: user?.id,
      owner_name: user?.full_name || user?.email,
      owner_role: user?.user_role || user?.role,
      total_members: 0,
      active_members: 0,
      total_hubs: 0,
      favorite_staff_count: 0,
      blocked_staff_count: 0,
    };

    createTeamMutation.mutate(teamData);
  };

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-4xl mx-auto">
        <Button
          variant="ghost"
          onClick={() => navigate(createPageUrl("Teams"))}
          className="mb-4 hover:bg-slate-100"
        >
          <ArrowLeft className="w-4 h-4 mr-2" />
          Back to Teams
        </Button>

        <div className="mb-8">
          <h1 className="text-3xl font-bold text-[#1C323E] mb-2">Create New Team</h1>
          <p className="text-slate-600">Set up your team to manage members and operations</p>
        </div>

        <form onSubmit={handleSubmit}>
          <Card className="border-slate-200 shadow-lg mb-6">
            <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b">
              <CardTitle className="flex items-center gap-2">
                <Users className="w-5 h-5 text-[#0A39DF]" />
                Team Information
              </CardTitle>
            </CardHeader>
            <CardContent className="p-6 space-y-6">
              {/* Company Logo */}
              <div>
                <Label className="text-sm font-semibold text-slate-700 mb-2 block">Company Logo</Label>
                <div className="flex items-center gap-4">
                  {formData.company_logo ? (
                    <img src={formData.company_logo} alt="Company Logo" className="w-24 h-24 rounded-xl object-cover border-2 border-slate-200" />
                  ) : (
                    <div className="w-24 h-24 bg-gradient-to-br from-[#0A39DF] to-[#1C323E] rounded-xl flex items-center justify-center text-white text-3xl font-bold">
                      {formData.team_name?.charAt(0) || 'T'}
                    </div>
                  )}
                  <div>
                    <input
                      type="file"
                      id="logo"
                      accept="image/*"
                      onChange={handleLogoUpload}
                      className="hidden"
                    />
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => document.getElementById('logo').click()}
                      disabled={uploadingLogo}
                    >
                      <Upload className="w-4 h-4 mr-2" />
                      {uploadingLogo ? 'Uploading...' : 'Upload Logo'}
                    </Button>
                    <p className="text-xs text-slate-500 mt-2">PNG, JPG up to 10MB</p>
                  </div>
                </div>
              </div>

              {/* Team Name */}
              <div>
                <Label htmlFor="team_name" className="text-sm font-semibold text-slate-700">Team Name *</Label>
                <Input
                  id="team_name"
                  value={formData.team_name}
                  onChange={(e) => setFormData({ ...formData, team_name: e.target.value })}
                  placeholder="e.g., Legendary Event Staffing"
                  required
                  className="mt-1"
                />
              </div>

              {/* Personal Info */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="full_name" className="text-sm font-semibold text-slate-700">Full Name</Label>
                  <Input
                    id="full_name"
                    value={formData.full_name}
                    onChange={(e) => setFormData({ ...formData, full_name: e.target.value })}
                    placeholder="Jon Holt"
                    className="mt-1"
                  />
                </div>
                <div>
                  <Label htmlFor="email" className="text-sm font-semibold text-slate-700">Email</Label>
                  <Input
                    id="email"
                    type="email"
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    placeholder="JonHolt@LegendaryEXE.com"
                    className="mt-1"
                  />
                </div>
              </div>

              <div>
                <Label htmlFor="phone" className="text-sm font-semibold text-slate-700">Phone</Label>
                <Input
                  id="phone"
                  value={formData.phone}
                  onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                  placeholder="+55 (41) 9797-7777"
                  className="mt-1"
                />
              </div>

              {/* Contact Info */}
              <div>
                <Label htmlFor="address" className="text-sm font-semibold text-slate-700">Address</Label>
                <Input
                  id="address"
                  value={formData.address}
                  onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                  placeholder="276 Redwood Shores, Redwood City, CA 94065, USA"
                  className="mt-1"
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="city" className="text-sm font-semibold text-slate-700">City</Label>
                  <Input
                    id="city"
                    value={formData.city}
                    onChange={(e) => setFormData({ ...formData, city: e.target.value })}
                    placeholder="Redwood City"
                    className="mt-1"
                  />
                </div>
                <div>
                  <Label htmlFor="zip_code" className="text-sm font-semibold text-slate-700">ZIP Code</Label>
                  <Input
                    id="zip_code"
                    value={formData.zip_code}
                    onChange={(e) => setFormData({ ...formData, zip_code: e.target.value })}
                    placeholder="94065"
                    className="mt-1"
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          <div className="flex justify-end gap-3">
            <Button
              type="button"
              variant="outline"
              onClick={() => navigate(createPageUrl("Teams"))}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              className="bg-[#0A39DF] hover:bg-[#0A39DF]/90"
              disabled={createTeamMutation.isPending}
            >
              <Save className="w-4 h-4 mr-2" />
              {createTeamMutation.isPending ? 'Creating...' : 'Create Team'}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}