import React, { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { Button } from "@/common/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/common/components/ui/card";
import { Input } from "@/common/components/ui/input";
import { Label } from "@/common/components/ui/label";
import { Textarea } from "@/common/components/ui/textarea";
import { 
  Select, 
  SelectContent, 
  SelectItem, 
  SelectTrigger, 
  SelectValue 
} from "@/common/components/ui/select";
import { ArrowLeft, Save, Loader2, Building2, User, MapPin, CreditCard, Activity } from "lucide-react";
import DashboardLayout from "@/features/layouts/DashboardLayout";
import { 
  useGetBusinessById, 
  useUpdateBusiness 
} from "@/dataconnect-generated/react";
import { 
  BusinessArea, 
  BusinessSector, 
  BusinessStatus, 
  BusinessRateGroup 
} from "@/dataconnect-generated";
import { dataConnect } from "@/features/auth/firebase";

export default function EditClient() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { id: businessId } = useParams<{ id: string }>();

  const { data: businessData, isLoading: isLoadingBusiness } = useGetBusinessById(dataConnect, { id: businessId || "" });
  const { mutateAsync: updateBusiness, isPending: isUpdating } = useUpdateBusiness(dataConnect);

  const [formData, setFormData] = useState({
    businessName: "",
    sector: BusinessSector.OTHER,
    address: "",
    city: "",
    area: BusinessArea.OTHER,
    contactName: "",
    phone: "",
    email: "",
    rateGroup: BusinessRateGroup.STANDARD,
    status: BusinessStatus.ACTIVE,
    notes: ""
  });

  useEffect(() => {
    if (businessData?.business) {
      const b = businessData.business;
      setFormData({
        businessName: b.businessName || "",
        sector: b.sector || BusinessSector.OTHER,
        address: b.address || "",
        city: b.city || "",
        area: b.area || BusinessArea.OTHER,
        contactName: b.contactName || "",
        phone: b.phone || "",
        email: b.email || "",
        rateGroup: b.rateGroup || BusinessRateGroup.STANDARD,
        status: b.status || BusinessStatus.ACTIVE,
        notes: b.notes || ""
      });
    }
  }, [businessData]);

  const handleChange = (field: string, value: any) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!businessId) return;

    try {
      await updateBusiness({
        id: businessId,
        businessName: formData.businessName,
        contactName: formData.contactName,
        phone: formData.phone,
        email: formData.email,
        address: formData.address,
        city: formData.city,
        area: formData.area,
        sector: formData.sector,
        rateGroup: formData.rateGroup,
        status: formData.status,
        notes: formData.notes
      });

      queryClient.invalidateQueries({ queryKey: ['businesses'] });
      queryClient.invalidateQueries({ queryKey: ['business', businessId] });
      navigate("/clients");
    } catch (error) {
      console.error("Error updating client:", error);
    }
  };

  if (isLoadingBusiness) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  if (!businessData?.business) {
    return (
      <DashboardLayout title="Client Not Found">
        <div className="text-center py-20">
          <h2 className="text-2xl font-bold mb-4">Business record not found.</h2>
          <Button onClick={() => navigate("/clients")} variant="outline">
            Return to Directory
          </Button>
        </div>
      </DashboardLayout>
    );
  }

  return (
    <DashboardLayout
      title={`Edit ${formData.businessName}`}
      subtitle="Update client partnership details and configuration."
      actions={
        <Button
          variant="outline"
          onClick={() => navigate("/clients")}
          leadingIcon={<ArrowLeft />}
        >
          Back to Directory
        </Button>
      }
    >
      <div className="max-w-4xl mx-auto pb-20">
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* General Information */}
          <Card className="border-border/50 shadow-sm">
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2">
                <Building2 className="w-5 h-5 text-primary" />
                General Information
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="businessName">Business Name *</Label>
                  <Input
                    id="businessName"
                    value={formData.businessName}
                    onChange={(e) => handleChange('businessName', e.target.value)}
                    required
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="sector">Industry / Sector *</Label>
                  <Select 
                    value={formData.sector} 
                    onValueChange={(value: BusinessSector) => handleChange('sector', value)}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select sector" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value={BusinessSector.BON_APPETIT}>Bon Appétit</SelectItem>
                      <SelectItem value={BusinessSector.EUREST}>Eurest</SelectItem>
                      <SelectItem value={BusinessSector.ARAMARK}>Aramark</SelectItem>
                      <SelectItem value={BusinessSector.EPICUREAN_GROUP}>Epicurean Group</SelectItem>
                      <SelectItem value={BusinessSector.CHARTWELLS}>Chartwells</SelectItem>
                      <SelectItem value={BusinessSector.OTHER}>Other</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Billing Information */}
          <Card className="border-border/50 shadow-sm">
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2">
                <MapPin className="w-5 h-5 text-primary" />
                Billing Information
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="address">Billing Address *</Label>
                <Input
                  id="address"
                  value={formData.address}
                  onChange={(e) => handleChange('address', e.target.value)}
                  required
                />
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="city">City *</Label>
                  <Input
                    id="city"
                    value={formData.city}
                    onChange={(e) => handleChange('city', e.target.value)}
                    required
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="area">Area</Label>
                  <Select 
                    value={formData.area} 
                    onValueChange={(value: BusinessArea) => handleChange('area', value)}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select area" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value={BusinessArea.BAY_AREA}>Bay Area</SelectItem>
                      <SelectItem value={BusinessArea.SOUTHERN_CALIFORNIA}>Southern California</SelectItem>
                      <SelectItem value={BusinessArea.NORTHERN_CALIFORNIA}>Northern California</SelectItem>
                      <SelectItem value={BusinessArea.CENTRAL_VALLEY}>Central Valley</SelectItem>
                      <SelectItem value={BusinessArea.OTHER}>Other</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Primary Contact */}
          <Card className="border-border/50 shadow-sm">
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2">
                <User className="w-5 h-5 text-primary" />
                Primary Contact
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="contactName">Contact Name *</Label>
                <Input
                  id="contactName"
                  value={formData.contactName}
                  onChange={(e) => handleChange('contactName', e.target.value)}
                  required
                />
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="phone">Phone Number</Label>
                  <Input
                    id="phone"
                    type="tel"
                    value={formData.phone}
                    onChange={(e) => handleChange('phone', e.target.value)}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="email">Email *</Label>
                  <Input
                    id="email"
                    type="email"
                    value={formData.email}
                    onChange={(e) => handleChange('email', e.target.value)}
                    required
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Rate Configuration & Status */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Card className="border-border/50 shadow-sm">
              <CardHeader>
                <CardTitle className="text-lg flex items-center gap-2">
                  <CreditCard className="w-5 h-5 text-primary" />
                  Rate Configuration
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  <Label htmlFor="rateGroup">Rate Group *</Label>
                  <Select 
                    value={formData.rateGroup} 
                    onValueChange={(value: BusinessRateGroup) => handleChange('rateGroup', value)}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select rate group" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value={BusinessRateGroup.STANDARD}>Standard</SelectItem>
                      <SelectItem value={BusinessRateGroup.PREMIUM}>Premium</SelectItem>
                      <SelectItem value={BusinessRateGroup.ENTERPRISE}>Enterprise</SelectItem>
                      <SelectItem value={BusinessRateGroup.CUSTOM}>Custom</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </CardContent>
            </Card>

            <Card className="border-border/50 shadow-sm">
              <CardHeader>
                <CardTitle className="text-lg flex items-center gap-2">
                  <Activity className="w-5 h-5 text-primary" />
                  Partnership Status
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  <Label htmlFor="status">Client Status *</Label>
                  <Select 
                    value={formData.status} 
                    onValueChange={(value: BusinessStatus) => handleChange('status', value)}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select status" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value={BusinessStatus.ACTIVE}>Active</SelectItem>
                      <SelectItem value={BusinessStatus.PENDING}>Pending</SelectItem>
                      <SelectItem value={BusinessStatus.INACTIVE}>Inactive</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Notes */}
          <Card className="border-border/50 shadow-sm">
            <CardHeader>
              <CardTitle className="text-lg">Notes</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                <Label htmlFor="notes">Additional Notes</Label>
                <Textarea
                  id="notes"
                  value={formData.notes}
                  onChange={(e) => handleChange('notes', e.target.value)}
                  rows={4}
                  placeholder="Internal notes about this partnership..."
                />
              </div>
            </CardContent>
          </Card>

          <div className="flex justify-end gap-3 pt-4">
            <Button
              type="button"
              variant="outline"
              onClick={() => navigate("/clients")}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={isUpdating}
              leadingIcon={isUpdating ? <Loader2 className="animate-spin" /> : <Save />}
            >
              {isUpdating ? "Saving Changes..." : "Save Client Details"}
            </Button>
          </div>
        </form>
      </div>
    </DashboardLayout>
  );
}
