import React, { forwardRef, useState } from "react";
import { BaseComponentProps, User } from "../../types";
import { Button } from "../ui/Button";
import { Input } from "../ui/Input";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/Card";

export interface UserProfileProps extends BaseComponentProps {
  user: User;
  editable?: boolean;
  onSave?: (updatedUser: Partial<User>) => void;
  onCancel?: () => void;
  loading?: boolean;
  fields?: Array<{
    key: keyof User;
    label: string;
    type?: "text" | "email" | "tel";
    editable?: boolean;
  }>;
}

const defaultFields = [
  {
    key: "name" as keyof User,
    label: "Full Name",
    type: "text" as const,
    editable: true,
  },
  {
    key: "email" as keyof User,
    label: "Email",
    type: "email" as const,
    editable: true,
  },
  {
    key: "role" as keyof User,
    label: "Role",
    type: "text" as const,
    editable: false,
  },
  {
    key: "created_at" as keyof User,
    label: "Member Since",
    type: "text" as const,
    editable: false,
  },
];

export const UserProfile = forwardRef<HTMLDivElement, UserProfileProps>(
  (
    {
      className = "",
      user,
      editable = false,
      onSave,
      onCancel,
      loading = false,
      fields = defaultFields,
      ...props
    },
    ref
  ) => {
    const [isEditing, setIsEditing] = useState(false);
    const [formData, setFormData] = useState<Partial<User>>(user);

    const handleEdit = () => {
      setIsEditing(true);
      setFormData(user);
    };

    const handleCancel = () => {
      setIsEditing(false);
      setFormData(user);
      onCancel?.();
    };

    const handleSave = () => {
      onSave?.(formData);
      setIsEditing(false);
    };

    const handleInputChange = (key: keyof User, value: string) => {
      setFormData((prev) => ({
        ...prev,
        [key]: value,
      }));
    };

    const formatFieldValue = (key: keyof User, value: string | undefined) => {
      if (key === "created_at" && value) {
        return new Date(value).toLocaleDateString();
      }
      if (key === "updated_at" && value) {
        return new Date(value).toLocaleDateString();
      }
      return value || "—";
    };

    const renderAvatarSection = () => (
      <div className="flex flex-col items-center mb-6">
        <div className="relative">
          {user.avatar_url ? (
            <img
              className="w-24 h-24 rounded-full border-4 border-white shadow-lg"
              src={user.avatar_url}
              alt={user.name || "User avatar"}
            />
          ) : (
            <div className="w-24 h-24 rounded-full border-4 border-white shadow-lg bg-gray-300 flex items-center justify-center">
              <span className="text-2xl font-bold text-gray-700">
                {user.name?.charAt(0) || user.email?.charAt(0) || "U"}
              </span>
            </div>
          )}

          {editable && isEditing && (
            <button className="absolute bottom-0 right-0 bg-primary-600 text-white rounded-full p-2 shadow-lg hover:bg-primary-700 transition-colors">
              <svg
                className="w-4 h-4"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"
                />
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"
                />
              </svg>
            </button>
          )}
        </div>

        <h2 className="mt-4 text-xl font-semibold text-gray-900 dark:text-white">
          {user.name || "Unnamed User"}
        </h2>
        <p className="text-sm text-gray-500 dark:text-gray-400">{user.email}</p>
        {user.role && (
          <span className="mt-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
            {user.role.charAt(0).toUpperCase() + user.role.slice(1)}
          </span>
        )}
      </div>
    );

    const renderField = (field: (typeof fields)[0]) => {
      const value = user[field.key];

      if (isEditing && field.editable) {
        return (
          <div key={field.key} className="space-y-2">
            <Input
              label={field.label}
              type={field.type}
              value={(formData[field.key] as string) || ""}
              onChange={(e) => handleInputChange(field.key, e.target.value)}
              disabled={loading}
            />
          </div>
        );
      }

      return (
        <div key={field.key} className="space-y-2">
          <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
            {field.label}
          </label>
          <p className="text-sm text-gray-900 dark:text-gray-100">
            {formatFieldValue(field.key, value as string | undefined)}
          </p>
        </div>
      );
    };

    return (
      <Card ref={ref} className={className} {...props}>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>Profile Information</CardTitle>
            {editable && !isEditing && (
              <Button
                variant="outline"
                size="sm"
                onClick={handleEdit}
                disabled={loading}
              >
                <svg
                  className="w-4 h-4 mr-2"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
                  />
                </svg>
                Edit
              </Button>
            )}
          </div>
        </CardHeader>

        <CardContent>
          {renderAvatarSection()}

          <div className="space-y-4">{fields.map(renderField)}</div>

          {isEditing && (
            <div className="flex items-center justify-end space-x-3 mt-6 pt-6 border-t border-gray-200 dark:border-gray-700">
              <Button
                variant="outline"
                onClick={handleCancel}
                disabled={loading}
              >
                Cancel
              </Button>
              <Button onClick={handleSave} loading={loading} disabled={loading}>
                Save Changes
              </Button>
            </div>
          )}
        </CardContent>
      </Card>
    );
  }
);

UserProfile.displayName = "UserProfile";
