import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Link } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { MapPin, Plus, Search, Building2, Edit } from "lucide-react";
import PageHeader from "@/components/common/PageHeader";

export default function SectorManagement() {
  const [searchTerm, setSearchTerm] = useState("");

  const { data: sectors = [], isLoading } = useQuery({
    queryKey: ['sectors'],
    queryFn: () => base44.entities.Sector.list('-created_date'),
    initialData: [],
  });

  const filteredSectors = sectors.filter(s =>
    !searchTerm ||
    s.sector_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    s.sector_code?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const getSectorColor = (index) => {
    const colors = [
      "from-blue-500 to-blue-700",
      "from-green-500 to-green-700",
      "from-purple-500 to-purple-700",
      "from-orange-500 to-orange-700",
    ];
    return colors[index % colors.length];
  };

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        <PageHeader
          title="Sector Management"
          subtitle={`${filteredSectors.length} sectors • Operating brands`}
          actions={
            <Link to={createPageUrl("AddSector")}>
              <Button className="bg-[#0A39DF] hover:bg-[#0A39DF]/90">
                <Plus className="w-4 h-4 mr-2" />
                Add Sector
              </Button>
            </Link>
          }
        />

        {/* Search */}
        <Card className="mb-6 border-slate-200">
          <CardContent className="p-4">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-slate-400" />
              <Input
                placeholder="Search sectors..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
          </CardContent>
        </Card>

        {/* Sectors Grid */}
        {isLoading ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {[...Array(6)].map((_, i) => (
              <div key={i} className="h-64 bg-slate-100 animate-pulse rounded-xl" />
            ))}
          </div>
        ) : filteredSectors.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredSectors.map((sector, index) => (
              <Card key={sector.id} className="border-2 border-slate-200 hover:border-[#0A39DF] hover:shadow-xl transition-all">
                <CardContent className="p-6">
                  <div className="flex items-start gap-4 mb-4">
                    <div className={`w-12 h-12 bg-gradient-to-br ${getSectorColor(index)} rounded-xl flex items-center justify-center text-white font-bold`}>
                      <MapPin className="w-6 h-6" />
                    </div>
                    <div className="flex-1">
                      <h3 className="font-bold text-lg text-[#1C323E] mb-1">
                        {sector.sector_name}
                      </h3>
                      <p className="text-sm text-slate-500">{sector.sector_code}</p>
                    </div>
                    <Link to={createPageUrl(`EditSector?id=${sector.id}`)}>
                      <Button variant="ghost" size="icon" className="text-slate-400 hover:text-[#0A39DF] hover:bg-blue-50">
                        <Edit className="w-4 h-4" />
                      </Button>
                    </Link>
                  </div>

                  <div className="space-y-3 mb-4">
                    {sector.parent_enterprise_name && (
                      <div className="flex items-center gap-2">
                        <Building2 className="w-4 h-4 text-slate-400" />
                        <span className="text-sm text-slate-600">{sector.parent_enterprise_name}</span>
                      </div>
                    )}
                    {sector.sector_type && (
                      <div>
                        <Badge variant="outline">{sector.sector_type}</Badge>
                      </div>
                    )}
                  </div>

                  {sector.client_portfolio && sector.client_portfolio.length > 0 && (
                    <div className="pt-4 border-t border-slate-200">
                      <p className="text-sm text-slate-600">
                        {sector.client_portfolio.length} Partners
                      </p>
                    </div>
                  )}
                </CardContent>
              </Card>
            ))}
          </div>
        ) : (
          <Card className="border-slate-200">
            <CardContent className="p-12 text-center">
              <MapPin className="w-16 h-16 mx-auto text-slate-300 mb-4" />
              <h3 className="text-xl font-semibold text-slate-700 mb-2">No Sectors Found</h3>
              <p className="text-slate-500 mb-6">Add your first sector</p>
              <Link to={createPageUrl("AddSector")}>
                <Button className="bg-[#0A39DF] hover:bg-[#0A39DF]/90">
                  <Plus className="w-4 h-4 mr-2" />
                  Add First Sector
                </Button>
              </Link>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}