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 { Building2, ArrowLeft, Save, Loader2 } from "lucide-react";
import PageHeader from "../components/common/PageHeader";
import { useToast } from "@/components/ui/use-toast";

export default function EditEnterprise() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { toast } = useToast();
  
  const urlParams = new URLSearchParams(window.location.search);
  const enterpriseId = urlParams.get('id');

  const { data: enterprises = [] } = useQuery({
    queryKey: ['enterprises'],
    queryFn: () => base44.entities.Enterprise.list(),
    initialData: [],
  });

  const enterprise = enterprises.find(e => e.id === enterpriseId);

  const [enterpriseData, setEnterpriseData] = useState({
    enterprise_number: "",
    enterprise_name: "",
    enterprise_code: "",
    brand_family: [],
    headquarters_address: "",
    global_policies: {
      minimum_wage: 16.50,
      overtime_rules: "Time and half after 8 hours",
      uniform_standards: "",
      background_check_required: true
    },
    rate_guardrails: {
      minimum_markup_percentage: 15,
      maximum_markup_percentage: 35,
      minimum_bill_rate: 18.00
    },
    primary_contact_name: "",
    primary_contact_email: "",
    is_active: true
  });

  const [brandInput, setBrandInput] = useState("");

  React.useEffect(() => {
    if (enterprise) {
      setEnterpriseData({
        enterprise_number: enterprise.enterprise_number || "",
        enterprise_name: enterprise.enterprise_name || "",
        enterprise_code: enterprise.enterprise_code || "",
        brand_family: enterprise.brand_family || [],
        headquarters_address: enterprise.headquarters_address || "",
        global_policies: enterprise.global_policies || {
          minimum_wage: 16.50,
          overtime_rules: "Time and half after 8 hours",
          uniform_standards: "",
          background_check_required: true
        },
        rate_guardrails: enterprise.rate_guardrails || {
          minimum_markup_percentage: 15,
          maximum_markup_percentage: 35,
          minimum_bill_rate: 18.00
        },
        primary_contact_name: enterprise.primary_contact_name || "",
        primary_contact_email: enterprise.primary_contact_email || "",
        is_active: enterprise.is_active !== undefined ? enterprise.is_active : true
      });
    }
  }, [enterprise]);

  const updateEnterpriseMutation = useMutation({
    mutationFn: ({ id, data }) => base44.entities.Enterprise.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['enterprises'] });
      toast({
        title: "Enterprise Updated",
        description: "Enterprise has been successfully updated",
      });
      navigate(createPageUrl("EnterpriseManagement"));
    },
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    updateEnterpriseMutation.mutate({ id: enterpriseId, data: enterpriseData });
  };

  const handleAddBrand = () => {
    if (brandInput.trim()) {
      setEnterpriseData({
        ...enterpriseData,
        brand_family: [...enterpriseData.brand_family, brandInput.trim()]
      });
      setBrandInput("");
    }
  };

  const handleRemoveBrand = (index) => {
    setEnterpriseData({
      ...enterpriseData,
      brand_family: enterpriseData.brand_family.filter((_, i) => i !== index)
    });
  };

  if (!enterprise) {
    return (
      <div className="p-8 text-center">
        <Loader2 className="w-8 h-8 animate-spin text-[#0A39DF] mx-auto mb-4" />
        <h2 className="text-2xl font-bold text-slate-900 mb-4">Loading Enterprise...</h2>
      </div>
    );
  }

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-4xl mx-auto">
        <PageHeader
          title="Edit Enterprise"
          subtitle={`Update information for ${enterprise.enterprise_name}`}
          backTo={createPageUrl("EnterpriseManagement")}
          backButtonLabel="Back to Enterprises"
        />

        <form onSubmit={handleSubmit}>
          <Card className="mb-6 border-slate-200 shadow-lg">
            <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b">
              <CardTitle className="flex items-center gap-2">
                <Building2 className="w-5 h-5 text-[#0A39DF]" />
                Basic Information
              </CardTitle>
            </CardHeader>
            <CardContent className="p-6 space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <Label htmlFor="enterprise_number">Enterprise Number</Label>
                  <Input
                    id="enterprise_number"
                    value={enterpriseData.enterprise_number}
                    readOnly
                    className="bg-slate-50 font-mono"
                  />
                  <p className="text-xs text-slate-500 mt-1">Auto-generated unique ID</p>
                </div>

                <div>
                  <Label htmlFor="enterprise_code">Enterprise Code *</Label>
                  <Input
                    id="enterprise_code"
                    placeholder="e.g., COMP"
                    value={enterpriseData.enterprise_code}
                    onChange={(e) => setEnterpriseData({...enterpriseData, enterprise_code: e.target.value.toUpperCase()})}
                    required
                  />
                </div>

                <div className="md:col-span-2">
                  <Label htmlFor="enterprise_name">Enterprise Name *</Label>
                  <Input
                    id="enterprise_name"
                    placeholder="e.g., Compass Group"
                    value={enterpriseData.enterprise_name}
                    onChange={(e) => setEnterpriseData({...enterpriseData, enterprise_name: e.target.value})}
                    required
                  />
                </div>

                <div>
                  <Label htmlFor="primary_contact_name">Primary Contact Name</Label>
                  <Input
                    id="primary_contact_name"
                    placeholder="John Doe"
                    value={enterpriseData.primary_contact_name}
                    onChange={(e) => setEnterpriseData({...enterpriseData, primary_contact_name: e.target.value})}
                  />
                </div>

                <div>
                  <Label htmlFor="primary_contact_email">Primary Contact Email</Label>
                  <Input
                    id="primary_contact_email"
                    type="email"
                    placeholder="john@enterprise.com"
                    value={enterpriseData.primary_contact_email}
                    onChange={(e) => setEnterpriseData({...enterpriseData, primary_contact_email: e.target.value})}
                  />
                </div>
              </div>

              <div>
                <Label htmlFor="headquarters_address">Headquarters Address</Label>
                <Textarea
                  id="headquarters_address"
                  placeholder="123 Main St, City, State ZIP"
                  value={enterpriseData.headquarters_address}
                  onChange={(e) => setEnterpriseData({...enterpriseData, headquarters_address: e.target.value})}
                  rows={2}
                />
              </div>

              <div>
                <Label>Brand Family</Label>
                <div className="flex gap-2 mb-2">
                  <Input
                    placeholder="Add brand (e.g., Bon Appétit)"
                    value={brandInput}
                    onChange={(e) => setBrandInput(e.target.value)}
                    onKeyPress={(e) => {
                      if (e.key === 'Enter') {
                        e.preventDefault();
                        handleAddBrand();
                      }
                    }}
                  />
                  <Button type="button" onClick={handleAddBrand} variant="outline">
                    Add
                  </Button>
                </div>
                <div className="flex flex-wrap gap-2">
                  {enterpriseData.brand_family.map((brand, index) => (
                    <div key={index} className="bg-blue-100 text-blue-800 px-3 py-1 rounded-full flex items-center gap-2">
                      <span>{brand}</span>
                      <button
                        type="button"
                        onClick={() => handleRemoveBrand(index)}
                        className="text-blue-600 hover:text-blue-800"
                      >
                        ×
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="mb-6 border-slate-200 shadow-lg">
            <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b">
              <CardTitle>Rate Guardrails</CardTitle>
            </CardHeader>
            <CardContent className="p-6 space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <Label>Minimum Markup %</Label>
                  <Input
                    type="number"
                    value={enterpriseData.rate_guardrails.minimum_markup_percentage}
                    onChange={(e) => setEnterpriseData({
                      ...enterpriseData,
                      rate_guardrails: {...enterpriseData.rate_guardrails, minimum_markup_percentage: parseFloat(e.target.value)}
                    })}
                  />
                </div>
                <div>
                  <Label>Maximum Markup %</Label>
                  <Input
                    type="number"
                    value={enterpriseData.rate_guardrails.maximum_markup_percentage}
                    onChange={(e) => setEnterpriseData({
                      ...enterpriseData,
                      rate_guardrails: {...enterpriseData.rate_guardrails, maximum_markup_percentage: parseFloat(e.target.value)}
                    })}
                  />
                </div>
                <div>
                  <Label>Minimum Bill Rate</Label>
                  <Input
                    type="number"
                    step="0.01"
                    value={enterpriseData.rate_guardrails.minimum_bill_rate}
                    onChange={(e) => setEnterpriseData({
                      ...enterpriseData,
                      rate_guardrails: {...enterpriseData.rate_guardrails, minimum_bill_rate: parseFloat(e.target.value)}
                    })}
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          <div className="flex justify-end gap-3">
            <Button
              type="button"
              variant="outline"
              onClick={() => navigate(createPageUrl("EnterpriseManagement"))}
            >
              <ArrowLeft className="w-4 h-4 mr-2" />
              Cancel
            </Button>
            <Button
              type="submit"
              className="bg-[#0A39DF] hover:bg-[#0A39DF]/90"
              disabled={updateEnterpriseMutation.isPending}
            >
              {updateEnterpriseMutation.isPending ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Updating...
                </>
              ) : (
                <>
                  <Save className="w-4 h-4 mr-2" />
                  Update Enterprise
                </>
              )}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}