import { Building2, Menu, Search, Shield } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { UserButton } from '@/components/UserButton';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Sheet,
  SheetContent,
  SheetTrigger,
} from "@/components/ui/sheet";
import { useAuth } from '@/contexts/AuthContext';
import { siteSettingsApi } from '@/db/api';
import { supabase } from '@/db/supabase';

const Header = () => {
  const { user, profile } = useAuth();
  const navigate = useNavigate();
  const [siteSettings, setSiteSettings] = useState<any>({
    site_logo: null,
    site_name: 'LetsGoCappadocia',
    header_background: null,
  });

  useEffect(() => {
    loadSiteSettings();

    // Realtime subscription for site settings changes
    const channel = supabase
      .channel('site-settings-changes')
      .on(
        'postgres_changes',
        {
          event: '*',
          schema: 'public',
          table: 'site_settings',
        },
        (payload) => {
          console.log('Site ayarları güncellendi:', payload);
          loadSiteSettings();
        }
      )
      .subscribe();

    return () => {
      supabase.removeChannel(channel);
    };
  }, []);

  const loadSiteSettings = async () => {
    try {
      const data = await siteSettingsApi.getAll();
      const settingsObj: any = {};
      data.forEach((setting: any) => {
        settingsObj[setting.key] = setting.value;
      });
      setSiteSettings(settingsObj);
    } catch (error) {
      console.error('Site ayarları yüklenirken hata:', error);
    }
  };

  // Header arka plan stili
  const headerStyle = siteSettings.header_background
    ? {
        backgroundImage: `url(${siteSettings.header_background})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
      }
    : {};

  return (
    <header 
      className="sticky top-0 z-50 w-full border-b bg-gradient-to-r from-cyan-50 to-teal-50 dark:from-slate-900 dark:to-slate-950 backdrop-blur supports-[backdrop-filter]:bg-opacity-80"
      style={headerStyle}
    >
      <div className="container mx-auto flex h-16 items-center justify-between px-4">
        <div className="flex items-center gap-8">
          <Link to="/" className="flex items-center gap-2">
            {siteSettings.site_logo ? (
              <img 
                src={siteSettings.site_logo} 
                alt={siteSettings.site_name || 'Logo'} 
                className="h-8 w-auto object-contain"
              />
            ) : (
              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary text-white">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className="h-5 w-5"
                >
                  <path d="M22 10v6M2 10l10-7 10 7M2 10v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6M12 18v-5" />
                </svg>
              </div>
            )}
            <span className="text-xl font-bold tracking-tight text-foreground">
              {siteSettings.site_name || 'Medo.dev'}
            </span>
          </Link>

          <nav className="hidden md:flex items-center gap-6 text-sm font-medium">
            <Link to="/explore" className="text-muted-foreground hover:text-foreground transition-colors">Gezi Rehberleri</Link>
            <Link to="/explore" className="text-muted-foreground hover:text-foreground transition-colors">Keşfet</Link>
            <Link to="/explore" className="text-muted-foreground hover:text-foreground transition-colors">Oteller</Link>
            <Link to="/provider/info" className="text-primary hover:text-primary/80 transition-colors font-semibold flex items-center gap-1">
              <Building2 className="h-4 w-4" />
              Provider Ol
            </Link>
          </nav>
        </div>

        <div className="flex items-center gap-4">
          <div className="hidden lg:flex relative w-64">
            <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
            <Input
              type="search"
              placeholder="Destinasyona göre keşfet"
              className="pl-9 bg-white/50 border-none focus-visible:ring-1"
            />
          </div>

          <div className="flex items-center gap-2">
            {user ? (
              <UserButton />
            ) : (
              <>
                <Button variant="ghost" size="sm" asChild className="hidden sm:inline-flex">
                  <Link to="/sign-in">Giriş Yap</Link>
                </Button>
                <Button size="sm" asChild className="rounded-full px-6 bg-primary hover:bg-primary/90 hidden sm:inline-flex">
                  <Link to="/sign-up">Kayıt Ol</Link>
                </Button>
                <Button 
                  variant="outline" 
                  size="sm" 
                  asChild
                  className="hidden lg:inline-flex border-primary text-primary hover:bg-primary/10"
                >
                  <Link to="/sign-up?role=provider">Provider Ol</Link>
                </Button>
              </>
            )}
            
            <Sheet>
              <SheetTrigger asChild>
                <Button variant="ghost" size="icon" className="md:hidden">
                  <Menu className="h-6 w-6" />
                </Button>
              </SheetTrigger>
              <SheetContent side="right" className="w-[300px] sm:w-[400px] flex flex-col">
                <div className="flex-1 overflow-y-auto pr-2 -mr-2">
                  <nav className="flex flex-col gap-4 mt-8 pb-8">
                    <Link to="/" className="text-lg font-semibold">Ana Sayfa</Link>
                    <Link to="/explore" className="text-lg font-semibold">Gezi Rehberleri</Link>
                    <Link to="/explore" className="text-lg font-semibold">Keşfet</Link>
                    <Link to="/explore" className="text-lg font-semibold">Oteller</Link>
                    <Link to="/provider/info" className="text-lg font-semibold text-primary flex items-center gap-2">
                      <Building2 className="h-5 w-5" />
                      Provider Ol
                    </Link>
                    {user && (
                      <>
                        <Link to="/my-trips" className="text-lg font-semibold">Seyahat Planlarım</Link>
                        <Link to="/bookmarks" className="text-lg font-semibold">Kaydedilenler</Link>
                        <Link to="/journal" className="text-lg font-semibold">Günlük & Fotoğraflar</Link>
                        {profile?.role === 'admin' && (
                          <Link to="/admin" className="text-lg font-semibold text-primary">
                            <Shield className="inline-block h-4 w-4 mr-2" />
                            Admin Panel
                          </Link>
                        )}
                        {profile?.role === 'provider' && (
                          <Link to="/provider/dashboard" className="text-lg font-semibold text-primary">
                            <Building2 className="inline-block h-4 w-4 mr-2" />
                            Provider Dashboard
                          </Link>
                        )}
                      </>
                    )}
                    <div className="pt-4 border-t flex flex-col gap-2">
                      {user ? (
                        <>
                          <div className="px-2 py-2 text-sm text-muted-foreground">
                            @{profile?.username}
                          </div>
                          <UserButton />
                        </>
                      ) : (
                        <>
                          <Button asChild variant="outline" className="w-full">
                            <Link to="/sign-in">Giriş Yap</Link>
                          </Button>
                          <Button asChild className="w-full rounded-full bg-primary">
                            <Link to="/sign-up">Kayıt Ol</Link>
                          </Button>
                          <div className="relative my-2">
                            <div className="absolute inset-0 flex items-center">
                              <span className="w-full border-t" />
                            </div>
                            <div className="relative flex justify-center text-xs uppercase">
                              <span className="bg-background px-2 text-muted-foreground">veya</span>
                            </div>
                          </div>
                          <Button asChild variant="outline" className="w-full border-primary text-primary">
                            <Link to="/sign-up?role=provider">
                              <Building2 className="h-4 w-4 mr-2" />
                              Provider Olarak Kayıt Ol
                            </Link>
                          </Button>
                        </>
                      )}
                    </div>
                  </nav>
                </div>
              </SheetContent>
            </Sheet>
          </div>
        </div>
      </div>
    </header>
  );
};

export default Header;
