import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Header } from '@/components/layout/Header';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { ArrowLeft, MapPin, Star, Globe, Calendar, Edit, Building2 } from 'lucide-react';
import { Company } from '@/types/database';
import { supabase } from '@/integrations/supabase/client';
import { PropertyOwnerForm } from '@/components/admin/PropertyOwnerForm';
import { PropertyOwnerPhotoGallery } from '@/components/companies/PropertyOwnerPhotoGallery';
import { useAuth } from '@/hooks/useAuth';
import { useUserRole } from '@/hooks/useUserRole';
import { toast } from '@/hooks/use-toast';
import { submitCompanyUpdate } from '@/lib/companyHelpers';

export default function PropertyOwnerDetail() {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const [owner, setOwner] = useState<Company | null>(null);
  const [loading, setLoading] = useState(true);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const { user } = useAuth();
  const { isModerator } = useUserRole();

  useEffect(() => {
    if (slug) {
      fetchOwnerData();
    }
  }, [slug]);

  const fetchOwnerData = async () => {
    try {
      const { data, error } = await supabase
        .from('companies')
        .select('*')
        .eq('slug', slug)
        .eq('company_type', 'property_owner')
        .maybeSingle();

      if (error) throw error;
      setOwner(data);
    } catch (error) {
      console.error('Error fetching property owner:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleEditSubmit = async (data: any) => {
    try {
      await submitCompanyUpdate(
        owner!.id,
        data,
        user!.id
      );

      toast({
        title: "Edit Submitted",
        description: "Your edit has been submitted for review."
      });

      setIsEditModalOpen(false);
    } catch (error: any) {
      toast({
        title: "Error",
        description: error.message || "Failed to submit edit.",
        variant: "destructive"
      });
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="animate-pulse space-y-6">
            <div className="h-64 bg-muted rounded-lg"></div>
            <div className="h-8 bg-muted rounded w-1/2"></div>
          </div>
        </div>
      </div>
    );
  }

  if (!owner) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="text-center py-12">
            <h1 className="text-2xl font-bold mb-4">Property Owner Not Found</h1>
            <Button onClick={() => navigate('/owners')}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              Back to Property Owners
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <Header />
      
      <main className="container mx-auto px-4 py-8">
        {/* Back Button and Edit Button */}
        <div className="flex items-center justify-between mb-6">
          <Button variant="ghost" onClick={() => navigate('/owners')}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            Back to Property Owners
          </Button>
          
          <Button 
            variant="outline"
            onClick={() => {
              if (!user) {
                navigate('/auth');
              } else {
                setIsEditModalOpen(true);
              }
            }}
          >
            <Edit className="w-4 h-4 mr-2" />
            Edit Property Owner
          </Button>
        </div>

        {/* Hero Section */}
        <div className="relative mb-8">
          <div className="aspect-[21/9] bg-gradient-to-br from-primary/20 via-secondary/20 to-accent/20 rounded-lg overflow-hidden relative">
            {(owner.banner_image_url || owner.banner_image_id) ? (
              <img 
                src={owner.banner_image_url || `https://imagedelivery.net/X-2-mmiWukWxvAQQ2_o-7Q/${owner.banner_image_id}/public`} 
                alt={owner.name}
                className="w-full h-full object-cover"
              />
            ) : owner.logo_url ? (
              <div className="flex items-center justify-center h-full bg-background/90">
                <img 
                  src={owner.logo_url} 
                  alt={owner.name}
                  className="max-h-48 object-contain"
                />
              </div>
            ) : (
              <div className="flex items-center justify-center h-full">
                <Building2 className="w-24 h-24 opacity-50" />
              </div>
            )}
            
            <div className="absolute bottom-0 left-0 right-0 p-8 bg-gradient-to-t from-black/60 to-transparent">
              <div className="flex items-end justify-between">
                <div>
                  <Badge variant="outline" className="bg-black/20 text-white border-white/20 mb-2">
                    Property Owner
                  </Badge>
                  <h1 className="text-4xl md:text-6xl font-bold text-white mb-2">
                    {owner.name}
                  </h1>
                  {owner.headquarters_location && (
                    <div className="flex items-center text-white/90 text-lg">
                      <MapPin className="w-5 h-5 mr-2" />
                      {owner.headquarters_location}
                    </div>
                  )}
                </div>
                
                {owner.average_rating > 0 && (
                  <div className="bg-black/30 backdrop-blur-md rounded-lg p-6 text-center">
                    <div className="flex items-center gap-2 text-white mb-2">
                      <Star className="w-6 h-6 fill-yellow-400 text-yellow-400" />
                      <span className="text-3xl font-bold">
                        {owner.average_rating.toFixed(1)}
                      </span>
                    </div>
                    <div className="text-white/90 text-sm">
                      {owner.review_count} {owner.review_count === 1 ? "review" : "reviews"}
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Company Info */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
          {owner.founded_year && (
            <Card>
              <CardContent className="p-4 text-center">
                <Calendar className="w-6 h-6 text-primary mx-auto mb-2" />
                <div className="text-2xl font-bold">{owner.founded_year}</div>
                <div className="text-sm text-muted-foreground">Founded</div>
              </CardContent>
            </Card>
          )}
          {owner.website_url && (
            <Card>
              <CardContent className="p-4 text-center">
                <Globe className="w-6 h-6 text-primary mx-auto mb-2" />
                <a 
                  href={owner.website_url} 
                  target="_blank" 
                  rel="noopener noreferrer"
                  className="text-sm text-primary hover:underline break-all"
                >
                  Visit Website
                </a>
              </CardContent>
            </Card>
          )}
        </div>

        {/* Tabs */}
        <Tabs defaultValue="overview" className="w-full">
          <TabsList className="grid w-full grid-cols-2 md:grid-cols-3">
            <TabsTrigger value="overview">Overview</TabsTrigger>
            <TabsTrigger value="parks">Parks</TabsTrigger>
            <TabsTrigger value="photos">Photos</TabsTrigger>
          </TabsList>

          <TabsContent value="overview" className="space-y-6">
            {owner.description && (
              <Card>
                <CardContent className="p-6">
                  <h2 className="text-2xl font-bold mb-4">About</h2>
                  <p className="text-muted-foreground whitespace-pre-wrap">
                    {owner.description}
                  </p>
                </CardContent>
              </Card>
            )}
          </TabsContent>

          <TabsContent value="parks">
            <Card>
              <CardContent className="p-6">
                <p className="text-muted-foreground">Parks owned by {owner.name} will be displayed here.</p>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="photos">
            <PropertyOwnerPhotoGallery 
              propertyOwnerId={owner.id}
              propertyOwnerName={owner.name}
            />
          </TabsContent>
        </Tabs>
      </main>

      {/* Edit Modal */}
      <Dialog open={isEditModalOpen} onOpenChange={setIsEditModalOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <PropertyOwnerForm
            initialData={{
              id: owner.id,
              name: owner.name,
              slug: owner.slug,
              description: owner.description,
              person_type: owner.person_type as any,
              website_url: owner.website_url,
              founded_year: owner.founded_year,
              headquarters_location: owner.headquarters_location,
              banner_image_url: owner.banner_image_url,
              card_image_url: owner.card_image_url
            }}
            onSubmit={handleEditSubmit}
            onCancel={() => setIsEditModalOpen(false)}
          />
        </DialogContent>
      </Dialog>
    </div>
  );
}
